| 1 |
|
| 2 |
""" |
| 3 |
Copyright (c) 2018 Rolf Hempel, [email protected] |
| 4 |
|
| 5 |
This file is part of the PlanetarySystemStacker tool (PSS). |
| 6 |
https://github.com/Rolf-Hempel/PlanetarySystemStacker |
| 7 |
|
| 8 |
PSS is free software: you can redistribute it and/or modify |
| 9 |
it under the terms of the GNU General Public License as published by |
| 10 |
the Free Software Foundation, either version 3 of the License, or |
| 11 |
(at your option) any later version. |
| 12 |
|
| 13 |
This program is distributed in the hope that it will be useful, |
| 14 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 16 |
GNU General Public License for more details. |
| 17 |
|
| 18 |
You should have received a copy of the GNU General Public License |
| 19 |
along with PSS. If not, see <http://www.gnu.org/licenses/>. |
| 20 |
|
| 21 |
""" |
| 22 |
|
| 23 |
import os |
| 24 |
import cv2 |
| 25 |
import struct |
| 26 |
import datetime |
| 27 |
import numpy as np |
| 28 |
|
| 29 |
|
| 30 |
class SERParser(object): |
| 31 |
|
| 32 |
__author__ = 'Michal Powalko' |
| 33 |
__author_email__ = '[email protected]' |
| 34 |
__version__ = '1.1' |
| 35 |
__name__ = 'SER parser for PlanetarySystemStacker tool (PSS)' |
| 36 |
|
| 37 |
def __init__(self, ser_file, SER_16bit_shift_correction=True): |
| 38 |
""" |
| 39 |
Parse video files of type SER (8 or 16 bit). Provide access to individual frames based on |
| 40 |
the frame index. |
| 41 |
|
| 42 |
:param ser_file: Full name of the video file. |
| 43 |
:param SER_16bit_shift_correction: If True and the frame type is 16bit, the video frames |
| 44 |
are analyzed to find the number of unused high bits in |
| 45 |
pixel data. In read operations data are shifted up by |
| 46 |
this number of bits. |
| 47 |
""" |
| 48 |
super().__init__() |
| 49 |
|
| 50 |
self.warn_message = self.sanity_check(ser_file) |
| 51 |
|
| 52 |
self.fid = self.open_file(ser_file) |
| 53 |
|
| 54 |
self.header = self.read_header() |
| 55 |
|
| 56 |
self.frame_count = self.header['FrameCount'] |
| 57 |
|
| 58 |
self.frame_size = self.header['ImageWidth'] * \ |
| 59 |
self.header['ImageHeight'] * \ |
| 60 |
self.header['BytesPerPixel'] |
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
self.shift_pixels = 0 |
| 67 |
|
| 68 |
if self.header['PixelDepthPerPlane'] <= 8: |
| 69 |
self.PixelDepthPerPlane = np.dtype(np.uint8) |
| 70 |
else: |
| 71 |
|
| 72 |
|
| 73 |
self.PixelDepthPerPlane = np.dtype(np.uint16).newbyteorder('<') |
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
if SER_16bit_shift_correction: |
| 78 |
self.correct_dynamic_range() |
| 79 |
|
| 80 |
self.color = 8 <= self.header['ColorID'] <= 19 and self.header['DebayerPattern'] is not None \ |
| 81 |
or 100 <= self.header['ColorID'] <= 101 |
| 82 |
|
| 83 |
def sanity_check(self, ser_file): |
| 84 |
warn_message = None |
| 85 |
if not os.path.isfile(ser_file): |
| 86 |
raise IOError("File does not exist") |
| 87 |
elif os.stat(ser_file).st_size == 0: |
| 88 |
raise IOError("File is empty") |
| 89 |
else: |
| 90 |
with open(ser_file, 'rb') as fid: |
| 91 |
HEADER = fid.read(14).decode() |
| 92 |
if HEADER != 'LUCAM-RECORDER': |
| 93 |
warn_message = "File does not conform to SER format, first 14 characters of header are: '" + HEADER + "'" |
| 94 |
return warn_message |
| 95 |
|
| 96 |
def open_file(self, ser_file): |
| 97 |
return open(ser_file, 'rb') |
| 98 |
|
| 99 |
def read_header(self): |
| 100 |
""" |
| 101 |
Read the "Header" of SER file with fixed size of 178 Byte. |
| 102 |
|
| 103 |
:return: header Dictionary containing the both "raw" |
| 104 |
and "decoded" values of "header" |
| 105 |
""" |
| 106 |
|
| 107 |
KEYS = ('FileId', 'LuID', 'ColorID', 'LittleEndian', 'ImageWidth', |
| 108 |
'ImageHeight', 'PixelDepthPerPlane', 'FrameCount', 'Observer', |
| 109 |
'Instrument', 'Telescope', 'DateTime', 'DateTime_UTC') |
| 110 |
|
| 111 |
ColorID = {0: 'Grayscale', |
| 112 |
8: 'Force Bayer RGGB', |
| 113 |
9: 'Force Bayer GRBG', |
| 114 |
10: 'Force Bayer GBRG', |
| 115 |
11: 'Force Bayer BGGR', |
| 116 |
16: 'BAYER_CYYM', |
| 117 |
17: 'BAYER_YCMY', |
| 118 |
18: 'BAYER_YMCY', |
| 119 |
19: 'BAYER_MYYC', |
| 120 |
100: 'RGB', |
| 121 |
101: 'BGR'} |
| 122 |
|
| 123 |
header = {key: value.decode('latin1') if isinstance(value, bytes) else |
| 124 |
value for (key, value) in zip(KEYS, struct.unpack( |
| 125 |
'<14s 7i 40s 40s 40s 2q', self.fid.read(178)))} |
| 126 |
|
| 127 |
if header['ColorID'] == 8: |
| 128 |
header['DebayerPattern'] = cv2.COLOR_BayerRG2BGR |
| 129 |
elif header['ColorID'] == 9: |
| 130 |
header['DebayerPattern'] = cv2.COLOR_BayerGR2BGR |
| 131 |
elif header['ColorID'] == 10: |
| 132 |
header['DebayerPattern'] = cv2.COLOR_BayerGB2BGR |
| 133 |
elif header['ColorID'] == 11: |
| 134 |
header['DebayerPattern'] = cv2.COLOR_BayerBG2BGR |
| 135 |
else: |
| 136 |
header['DebayerPattern'] = None |
| 137 |
|
| 138 |
header['ColorIDDecoded'] = ColorID[header['ColorID']] |
| 139 |
|
| 140 |
if header['ColorID'] < 100: |
| 141 |
header['NumberOfPlanes'] = 1 |
| 142 |
else: |
| 143 |
header['NumberOfPlanes'] = 3 |
| 144 |
|
| 145 |
if header['PixelDepthPerPlane'] <= 8: |
| 146 |
header['BytesPerPixel'] = header['NumberOfPlanes'] |
| 147 |
if header['ColorID'] < 100: |
| 148 |
header['PixelDataOrganization'] = 'M' |
| 149 |
elif header['ColorID'] == 100: |
| 150 |
header['PixelDataOrganization'] = 'R G B' |
| 151 |
else: |
| 152 |
header['PixelDataOrganization'] = 'B G R' |
| 153 |
else: |
| 154 |
header['BytesPerPixel'] = 2 * header['NumberOfPlanes'] |
| 155 |
if header['ColorID'] < 100: |
| 156 |
header['PixelDataOrganization'] = 'MM' |
| 157 |
elif header['ColorID'] == 100: |
| 158 |
header['PixelDataOrganization'] = 'RR GG BB' |
| 159 |
else: |
| 160 |
header['PixelDataOrganization'] = 'BB GG RR' |
| 161 |
|
| 162 |
try: |
| 163 |
header['DateTime_Decoded'] = datetime.datetime(1, 1, 1) + \ |
| 164 |
datetime.timedelta(microseconds=header['DateTime'] // 10) |
| 165 |
except Exception: |
| 166 |
header['DateTime_Decoded'] = None |
| 167 |
|
| 168 |
try: |
| 169 |
header['DateTime_UTC_Decoded'] = datetime.datetime(1, 1, 1) + \ |
| 170 |
datetime.timedelta(microseconds=header['DateTime_UTC'] // 10) |
| 171 |
except Exception: |
| 172 |
header['DateTime_UTC_Decoded'] = None |
| 173 |
|
| 174 |
|
| 175 |
if 'fps=' in header['Telescope']: |
| 176 |
header['FPS'] = float(header['Telescope'].split('fps=')[1].split('gain')[0]) |
| 177 |
header['Gain'] = int(header['Telescope'].split('gain=')[1].split('exp')[0]) |
| 178 |
header['Exposure [ms]'] = float(header['Telescope'].split('exp=')[1].split('\x00')[0]) |
| 179 |
|
| 180 |
self.frame_number = -1 |
| 181 |
|
| 182 |
return header |
| 183 |
|
| 184 |
def read_frame_raw(self, frame_number=None): |
| 185 |
""" |
| 186 |
Read the "Image Data" of SER file. Return the 2D or 3D image data without changing the |
| 187 |
content (e.g. debayering or conversion to / from grayscale). |
| 188 |
|
| 189 |
:return: image_data: Multi dimmensional Numpy array containig image frame data. |
| 190 |
""" |
| 191 |
|
| 192 |
if frame_number is None: |
| 193 |
frame_number = self.frame_number + 1 |
| 194 |
|
| 195 |
if 0 <= frame_number < self.frame_count: |
| 196 |
if frame_number != self.frame_number + 1: |
| 197 |
if frame_number == 0: |
| 198 |
self.fid.seek(178) |
| 199 |
else: |
| 200 |
self.fid.seek(178 + frame_number * self.frame_size) |
| 201 |
else: |
| 202 |
raise IOError('Error in reading SER frame, index: {0} is out of bounds'.format(frame_number)) |
| 203 |
|
| 204 |
self.frame_number = frame_number |
| 205 |
|
| 206 |
if self.header['NumberOfPlanes'] == 1: |
| 207 |
|
| 208 |
if self.shift_pixels: |
| 209 |
return np.frombuffer(self.fid.read(self.frame_size), |
| 210 |
dtype=self.PixelDepthPerPlane).reshape( |
| 211 |
self.header['ImageHeight'], self.header['ImageWidth']) << self.shift_pixels |
| 212 |
else: |
| 213 |
return np.frombuffer(self.fid.read(self.frame_size), |
| 214 |
dtype=self.PixelDepthPerPlane).reshape( |
| 215 |
self.header['ImageHeight'], self.header['ImageWidth']) |
| 216 |
else: |
| 217 |
if self.shift_pixels: |
| 218 |
return np.frombuffer(self.fid.read(self.frame_size), |
| 219 |
dtype=self.PixelDepthPerPlane).reshape( |
| 220 |
self.header['ImageHeight'], |
| 221 |
self.header['ImageWidth'], |
| 222 |
self.header['NumberOfPlanes']) << self.shift_pixels |
| 223 |
else: |
| 224 |
return np.frombuffer(self.fid.read(self.frame_size), |
| 225 |
dtype=self.PixelDepthPerPlane).reshape( |
| 226 |
self.header['ImageHeight'], self.header['ImageWidth'], |
| 227 |
self.header['NumberOfPlanes']) |
| 228 |
|
| 229 |
def read_frame(self, frame_number=None): |
| 230 |
""" |
| 231 |
Read the "Image Data" of SER file. |
| 232 |
|
| 233 |
:return: image_data: Multi dimmensional Numpy array containig image frame data. |
| 234 |
""" |
| 235 |
|
| 236 |
if frame_number is None: |
| 237 |
frame_number = self.frame_number + 1 |
| 238 |
|
| 239 |
if 0 <= frame_number < self.frame_count: |
| 240 |
if frame_number != self.frame_number + 1: |
| 241 |
if frame_number == 0: |
| 242 |
self.fid.seek(178) |
| 243 |
else: |
| 244 |
self.fid.seek(178 + frame_number * self.frame_size) |
| 245 |
else: |
| 246 |
raise IOError('Error in reading SER frame, index: {0} is out of bounds'.format(frame_number)) |
| 247 |
|
| 248 |
self.frame_number = frame_number |
| 249 |
|
| 250 |
if self.header['NumberOfPlanes'] == 1: |
| 251 |
if self.color: |
| 252 |
return cv2.cvtColor( |
| 253 |
np.frombuffer(self.fid.read(self.frame_size), |
| 254 |
dtype=self.PixelDepthPerPlane).reshape( |
| 255 |
self.header['ImageHeight'], |
| 256 |
self.header['ImageWidth']), |
| 257 |
self.header['DebayerPattern']) |
| 258 |
else: |
| 259 |
return np.frombuffer(self.fid.read(self.frame_size), |
| 260 |
dtype=self.PixelDepthPerPlane).reshape( |
| 261 |
self.header['ImageHeight'], |
| 262 |
self.header['ImageWidth']) |
| 263 |
else: |
| 264 |
if self.header['ColorID'] == 101: |
| 265 |
return cv2.cvtColor( |
| 266 |
np.frombuffer(self.fid.read(self.frame_size), |
| 267 |
dtype=self.PixelDepthPerPlane).reshape( |
| 268 |
self.header['ImageHeight'], |
| 269 |
self.header['ImageWidth'], |
| 270 |
self.header['NumberOfPlanes']), |
| 271 |
cv2.COLOR_BGR2RGB) |
| 272 |
else: |
| 273 |
return np.frombuffer(self.fid.read(self.frame_size), |
| 274 |
dtype=self.PixelDepthPerPlane).reshape( |
| 275 |
self.header['ImageHeight'], |
| 276 |
self.header['ImageWidth'], |
| 277 |
self.header['NumberOfPlanes']) |
| 278 |
|
| 279 |
def read_all_frames(self): |
| 280 |
return [self.read_frame(idx) for idx in range(self.frame_count)] |
| 281 |
|
| 282 |
def correct_dynamic_range(self): |
| 283 |
""" |
| 284 |
Test if the pixel values in a sample of video frames use the full dynamic range of 16bit. |
| 285 |
To this end, for three frames (first frame, middle frame, last frame) the maximal value |
| 286 |
is determined. The "shift_pixels" parameter is set to the number of bits which are not used |
| 287 |
in all the pixels tested. After the call to this method, calls to "read_frame_raw" |
| 288 |
return frame values left-shifted by this number of bits. |
| 289 |
|
| 290 |
:return: - |
| 291 |
""" |
| 292 |
|
| 293 |
|
| 294 |
if self.frame_count > 2: |
| 295 |
frame_ids = [0, int(self.frame_count / 2), self.frame_count-1] |
| 296 |
else: |
| 297 |
frame_ids = [0] |
| 298 |
|
| 299 |
|
| 300 |
max_pixel_value = max([np.max(self.read_frame_raw(frame_id)) for frame_id in frame_ids]) |
| 301 |
|
| 302 |
|
| 303 |
|
| 304 |
self.shift_pixels = 16 - int(max_pixel_value).bit_length() |
| 305 |
|
| 306 |
|
| 307 |
def read_trailer(self): |
| 308 |
""" |
| 309 |
Read the "Trailer" of SER file with time stamps in UTC for every image |
| 310 |
frame. Those values are "optional". |
| 311 |
|
| 312 |
:return: trailer List containing "datetime" objects for |
| 313 |
time stamps in UTC. Otherwise "None" |
| 314 |
""" |
| 315 |
|
| 316 |
self.fid.seek(178 + self.frame_count * self.frame_size) |
| 317 |
|
| 318 |
content = self.fid.read() |
| 319 |
|
| 320 |
self.frame_number = self.frame_count |
| 321 |
|
| 322 |
if content: |
| 323 |
return [datetime.datetime(1, 1, 1) + datetime.timedelta( |
| 324 |
microseconds=value // 10) for value in struct.unpack( |
| 325 |
'<{0}Q'.format(self.frame_count), content)] |
| 326 |
else: |
| 327 |
return None |
| 328 |
|
| 329 |
def release(self): |
| 330 |
self.fid.close() |
| 331 |
|
| 332 |
|
| 333 |
if __name__ == "__main__": |
| 334 |
|
| 335 |
import ser_parser |
| 336 |
import matplotlib |
| 337 |
matplotlib.use('Agg') |
| 338 |
import matplotlib.pyplot as plt |
| 339 |
|
| 340 |
|
| 341 |
|
| 342 |
|
| 343 |
|
| 344 |
|
| 345 |
|
| 346 |
|
| 347 |
|
| 348 |
file_path = r'D:\SW-Development\Python\PlanetarySystemStacker\Examples\SER_Steffen-Elste\garten_1024x768-000001__16-18-36__data.ser' |
| 349 |
|
| 350 |
cap = ser_parser.SERParser(file_path) |
| 351 |
if cap.warn_message is not None: |
| 352 |
print (cap.warn_message) |
| 353 |
|
| 354 |
last_frame_read = cap.read_frame(3) |
| 355 |
frame_count = cap.frame_count |
| 356 |
shape = last_frame_read.shape |
| 357 |
color = cap.color |
| 358 |
dtype = cap.PixelDepthPerPlane |
| 359 |
all_frames = cap.read_all_frames() |
| 360 |
|
| 361 |
|
| 362 |
if color: |
| 363 |
plt.imshow(last_frame_read) |
| 364 |
else: |
| 365 |
plt.imshow(last_frame_read, cmap='gray') |
| 366 |
plt.show() |