-
Notifications
You must be signed in to change notification settings - Fork 1
/
decode_imagery.py
186 lines (144 loc) · 5.78 KB
/
decode_imagery.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# Input: Satnogs DB type files - 2023-05-21 09:26:37|A49EA68AB262E0A49EA68AB2626303F05701A40C000000086D0B0B0B0..... etc.
import argparse
import datetime
import math
import os.path
import numpy as np
from dateutil import parser as dateparser
import cv2
from PIL import Image
from PIL import ImageOps
def chunk2xy(chunk_num):
x_image = (chunk_num * 80) % 480
y_image = math.floor((chunk_num * 80) / 480)
return x_image, y_image
def write_pixel(imager, chunk_num):
global decoder_exception
x, y = chunk2xy(chunk_num)
for i in range(80):
# print(imager[i])
try:
im.putpixel((x + i, y), (imager[i], imager[i], imager[i]))
except Exception as e:
print(e)
print("Failed to write pixel")
pass
def parse(frame):
"""
struct{
uint16_t packetId; //0xA4 0x0C
uint16_t sequenceId; //ignore
uint8_t isPreview; //one indicates 48x36 pixel preview, zero indicates 480x360 full resolution image
uint16_t elementId; //image chunk number. 0-21 for previews, 0-2159 for full
uint8_t pixels[80]; //pixel data
}
"""
global decoder_exception
frame_bytes = bytearray.fromhex(frame)[18:]
packetID = int.from_bytes(frame_bytes[0:2], "big")
if len(frame_bytes) > 30 and packetID == 41996:
# print("GOOD FRAME!")
isPreview = frame_bytes[5]
elementID = int.from_bytes(frame_bytes[5:7], "big")
imagery = frame_bytes[7:] # imagery data
# print(f"{isPreview}\t{elementID}\t{imagery}")
if args.remove_preview:
if isPreview == 1:
imagery = None
else:
write_pixel(imagery, elementID)
else:
write_pixel(imagery, elementID)
try:
ids_frames.remove(elementID)
except:
pass
def gamma_correction(vals, gamma=2.2):
cc = 0.018
inv_gam = 1 / gamma
clip_val = (1.099 * np.power(cc, inv_gam) - 0.099) / cc
return np.where(vals < cc, vals * clip_val, 1.099 * np.power(vals, inv_gam) - 0.099)
if __name__ == "__main__":
argparser = argparse.ArgumentParser()
argparser.add_argument("--start_date", "-s", action="store")
argparser.add_argument("--end_date", "-e", action="store")
argparser.add_argument("--outputname", "-o", action="store",required=True)
argparser.add_argument("--remove_preview", "-rp", action="store_true")
argparser.add_argument("--equalize", "-ei", action="store_true")
argparser.add_argument("--write_fc", "-fc", action="store_true")
argparser.add_argument("--source_file", "-f", required=True, action="store")
args = argparser.parse_args()
start_datetime = (
dateparser.parse(args.start_date) if args.start_date else datetime.datetime.min
)
end_datetime = (
dateparser.parse(args.end_date) if args.end_date else datetime.datetime.max
)
print(f"Start date: {start_datetime}\tEnd date: {end_datetime}")
if args.remove_preview:
print("[WARN] Remove preview frames is on")
print("[WARN] This feature is beta and may not work correctly...")
if not os.path.exists(args.source_file):
raise ValueError("Source file does not exist.")
with open(args.source_file, "r") as f:
f_lines = f.read().split("\n")
f_frames = []
ids_frames = list(range(2160))
for line in f_lines:
line_parts = line.split("|")
if len(line_parts) >= 2:
frame_date = dateparser.parse(line_parts[0])
# print(f"{start_datetime} < {frame_date} < {end_datetime}")
if start_datetime < frame_date < end_datetime:
f_frames.append(line_parts[1])
print(f"Original frame count: {len(f_lines)}")
print(f"Filtered frame count: {len(f_frames)}")
# parsing
im = Image.new("RGB", (480, 360))
for i in range(len(f_frames)):
frame = f_frames[i]
parse(frame)
print("Writing images...")
im.save(str(args.outputname)+"_raw.png")
srcBGR = cv2.imread("output_raw.png", 0)
rgb = cv2.cvtColor(srcBGR, cv2.COLOR_BayerGR2RGB)
if args.write_fc:
print("Writing FC composite...")
rgb_gamma = gamma_correction(rgb, gamma=1)
img_float = rgb_gamma / rgb_gamma.max()
data = 255 * img_float
img_uint8 = data.astype(np.uint8)
Image.fromarray(img_uint8).save(str(args.outputname)+"_fc.png")
bw = cv2.cvtColor(srcBGR, cv2.COLOR_BayerGR2GRAY)
cv2.imwrite(str(args.outputname)+"_rgb.png", rgb)
cv2.imwrite(str(args.outputname)+"_bw.png", bw)
# post process - fill in blanks
im_blank = Image.open(str(args.outputname)+"_raw.png")
pixels = list(im_blank.getdata())
for z in range(len(ids_frames)):
bad_id = ids_frames[z]
x, y = chunk2xy(bad_id)
for i in range(80):
try:
im_blank.putpixel(
(x + i, y),
(
pixels[(y - 1) * 480 + x + i][0],
pixels[(y - 1) * 480 + x + i][0],
pixels[(y - 1) * 480 + x + i][0],
),
)
except:
print("Can't correct error")
im_blank.save(str(args.outputname)+"_smooth_raw.png")
# post process color
srcBGR = cv2.imread(str(args.outputname)+"_smooth_raw.png", 0)
rgb = cv2.cvtColor(srcBGR, cv2.COLOR_BayerGR2RGB)
bw = cv2.cvtColor(srcBGR, cv2.COLOR_BayerGR2GRAY)
cv2.imwrite(str(args.outputname)+"_smooth_rgb.png", rgb)
cv2.imwrite(str(args.outputname)+"_smooth_bw.png", bw)
if args.equalize:
print("Writing equalized image...")
i = Image.open(str(args.outputname)+"_smooth_rgb.png")
i = ImageOps.autocontrast(i)
i.save(str(args.outputname)+"_smooth_rgb_equalized.png",preserve_tone=True)