Debian Codegraph @

planetary_system_stacker/frames.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 # -*- coding: utf-8; -*-
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 from glob import glob
24 from math import ceil
25 from os import path, remove, listdir, stat
26 from os.path import splitext
27 from pathlib import Path
28 from time import time
29
30 from PyQt5 import QtCore
31 from astropy.io import fits
32 from cv2 import imread, VideoCapture, CAP_PROP_FRAME_COUNT, cvtColor, COLOR_RGB2GRAY, \
33 COLOR_BGR2RGB, COLOR_BayerGB2BGR, COLOR_BayerBG2BGR, THRESH_TOZERO, threshold, \
34 GaussianBlur, Laplacian, CV_32F, COLOR_RGB2BGR, imwrite, convertScaleAbs, CAP_PROP_POS_FRAMES, \
35 IMREAD_UNCHANGED, flip, COLOR_GRAY2RGB, COLOR_BayerRG2BGR, COLOR_BayerGR2BGR, \
36 COLOR_BayerRG2BGR_VNG, COLOR_BayerGR2BGR_VNG, COLOR_BayerGB2BGR_VNG, COLOR_BayerBG2BGR_VNG, \
37 COLOR_BayerRG2BGR_EA, COLOR_BayerGR2BGR_EA, COLOR_BayerGB2BGR_EA, COLOR_BayerBG2BGR_EA
38 from cv2 import mean as cv_mean
39 from numpy import max as np_max
40 from numpy import min as np_min
41 from numpy import sum as np_sum
42 from numpy import uint8, uint16, int32, float32, clip, zeros, float64, where, average, moveaxis, \
43 unravel_index, ndarray
44
45 import ser_parser
46 from configuration import Configuration
47 from exceptions import TypeError, ShapeError, ArgumentError, WrongOrderingError, Error, \
48 InternalError
49 from frames_old import FramesOld
50
51
52 def debayer_frame(frame_in, debayer_pattern='No change', debayer_method='Bilinear', BGR_input=False):
53 """
54 Process a given input frame "frame_in", either containing one layer (B/W) or three layers
55 (color) into an output frame "frame_out" as specified by the parameter "debayer_pattern".
56
57 The rules for this transformation are:
58 - If the "debayer_pattern" is "No change", the input frame is not changed, i.e. the
59 output frame is identical to the input frame. The same applies if the input frame is of type
60 "B/W" and the "debayer_pattern" is "Grayscale".
61 - If the input frame is of type "color" and "debayer_pattern" is "Grayscale", the RGB / BGR
62 image is converted into a B/W one.
63 - If the input frame is of type "color", the "debayer_pattern" is "BGR" and "BGR_input" is
64 'False', the "B" and "R" channels are exchanged. The same happens if "debayer_pattern" is "RGB"
65 and "BGR_input" is 'True'. For the other two combinations the channels are not exchanged.
66 - If the input frame is of type "Grayscale" and "debayer_pattern" is "RGB" or "BGR", the result
67 is a three-channel RGB / BGR image where all channels are the same.
68 - If a non-standard "debayer_pattern" (i.e. "RGGB", "GRBG", "GBRG", "BGGR") is specified and the
69 input is a B/W image, decode the image using the given Bayer pattern. If the input image is
70 of type "color" (three-channel RGB or BGR), first convert it into grayscale and then decode
71 the image as in the B/W case. In both cases the result is a three-channel RGB color image.
72
73 :param frame_in: Input image, either 2D (grayscale) or 3D (color). The type is either 8 or 16
74 bit unsigned int.
75 :param debayer_pattern: Pattern used to convert the input image into the output image. One out
76 of 'Grayscale', 'RGB', 'Force Bayer RGGB', 'Force Bayer GRBG',
77 'Force Bayer GBRG', 'Force Bayer BGGR'
78 :param BGR_input: If 'True', a color input frame is interpreted as 'BGR'; Otherwise as 'RGB'.
79 OpenCV reads color images in 'BGR' format.
80 :return: frame_out: output image (see above)
81 """
82 if debayer_method == 'Bilinear':
83 debayer_codes = {
84 'Force Bayer RGGB': COLOR_BayerRG2BGR,
85 'Force Bayer GRBG': COLOR_BayerGR2BGR,
86 'Force Bayer GBRG': COLOR_BayerGB2BGR,
87 'Force Bayer BGGR': COLOR_BayerBG2BGR
88 }
89 if debayer_method == 'Variable Number of Gradients':
90 debayer_codes = {
91 'Force Bayer RGGB': COLOR_BayerRG2BGR_VNG,
92 'Force Bayer GRBG': COLOR_BayerGR2BGR_VNG,
93 'Force Bayer GBRG': COLOR_BayerGB2BGR_VNG,
94 'Force Bayer BGGR': COLOR_BayerBG2BGR_VNG
95 }
96 if debayer_method == 'Edge Aware':
97 debayer_codes = {
98 'Force Bayer RGGB': COLOR_BayerRG2BGR_EA,
99 'Force Bayer GRBG': COLOR_BayerGR2BGR_EA,
100 'Force Bayer GBRG': COLOR_BayerGB2BGR_EA,
101 'Force Bayer BGGR': COLOR_BayerBG2BGR_EA
102 }
103
104 type_in = frame_in.dtype
105
106 if type_in != uint8 and type_in != uint16:
107 raise Exception("Image type " + str(type_in) + " not supported")
108
109 # If the input frame is 3D, it represents a color image.
110 color_in = len(frame_in.shape) == 3
111
112 # Case color input image.
113 if color_in:
114 # Three-channel input, interpret as RGB color and leave it unchanged.
115 if debayer_pattern == 'No change' or debayer_pattern == 'RGB' and not BGR_input or \
116 debayer_pattern == 'BGR' and BGR_input:
117 frame_out = frame_in
118
119 # If the Bayer pattern and the BGR_input flag don't match, flip channels.
120 elif debayer_pattern == 'RGB' and BGR_input or debayer_pattern == 'BGR' and not BGR_input:
121 frame_out = cvtColor(frame_in, COLOR_BGR2RGB)
122
123 # Three-channel (color) input, reduce to two-channel (B/W) image.
124 elif debayer_pattern in ['Grayscale', 'Force Bayer RGGB', 'Force Bayer GRBG',
125 'Force Bayer GBRG', 'Force Bayer BGGR']:
126
127 frame_2D = cvtColor(frame_in, COLOR_RGB2GRAY)
128
129 # Output is B/W image.
130 if debayer_pattern == 'Grayscale':
131 frame_out = frame_2D
132
133 # Decode the B/W image into a color image using a Bayer pattern.
134 else:
135 frame_out = cvtColor(frame_2D, debayer_codes[debayer_pattern])
136
137 # Invalid debayer pattern specified.
138 else:
139 raise Exception("Debayer pattern " + debayer_pattern + " not supported")
140
141 # Case B/W input image.
142 else:
143 # Two-channel input, interpret as B/W image and leave it unchanged.
144 if debayer_pattern in ['No change', 'Grayscale']:
145 frame_out = frame_in
146
147 # Transform the one-channel B/W image in an RGB one where all three channels are the same.
148 elif debayer_pattern == 'RGB' or debayer_pattern == 'BGR':
149 frame_out = cvtColor(frame_in, COLOR_GRAY2RGB)
150
151 # Non-standard Bayer pattern, decode into color image.
152 elif debayer_pattern in ['Force Bayer RGGB', 'Force Bayer GRBG',
153 'Force Bayer GBRG', 'Force Bayer BGGR']:
154 frame_out = cvtColor(frame_in, debayer_codes[debayer_pattern])
155
156 # Invalid Bayer pattern specified.
157 else:
158 raise Exception("Debayer pattern " + debayer_pattern + " not supported")
159
160 # Return the decoded image.
161 return frame_out
162
163
164 def detect_bayer(frame, frames_bayer_max_noise_diff_green, frames_bayer_min_distance_from_blue,
165 frames_color_difference_threshold):
166 """
167 Detect a Bayer pattern in a grayscale image. The assumption is that statistically the
168 brightness differences at adjacent pixels are greater than those at neighboring pixels of the
169 same color. It is also assumed that the noise in the blue channel is greater than in the red
170 and green channels.
171
172 Acknowledgements: This method uses an algorithm developed by Chris Garry for his 'PIPP'
173 software package.
174
175 :param frame: Numpy array (2D or 3D) of type uint8 or uint16 containing the image data.
176 :param frames_bayer_max_noise_diff_green: Maximum allowed difference in noise levels at the two
177 green pixels of the bayer matrix in percent of value
178 at the blue pixel.
179 :param frames_bayer_min_distance_from_blue: Maximum allowed noise level at Bayer matrix pixels
180 other than blue, in percent of value at the blue
181 pixel.
182 :param frames_color_difference_threshold: If the brightness values of all three color channels
183 of a three-channel frame at all pixels do not differ
184 by more than this value, the frame is regarded as
185 monochrome.
186
187 :return: If the input frame is a (3D) color image, 'Color' is returned.
188 If the input frame is a (2D or 3D) grayscale image without any detectable Bayer
189 pattern, 'Grayscale' is returned.
190 If a Bayer pattern is detected in the grayscale image, its type (one out of
191 'Force Bayer BGGR', 'Force Bayer GBRG', 'Force Bayer GRBG', 'Force Bayer RGGB') is
192 returned.
193 If none of the above is true, 'None' is returned.
194 """
195
196 # Frames are stored as 3D arrays. Test if all three color levels are the same.
197 if len(frame.shape) == 3 and frame.shape[2] == 3:
198 first_minus_second = np_max(
199 abs(frame[:, :, 0].astype(int32) - frame[:, :, 1].astype(int32)))
200 first_minus_third = np_max(abs(frame[:, :, 0].astype(int32) - frame[:, :, 2].astype(int32)))
201 # print("first_minus_second: " + str(first_minus_second) + ", first_minus_third: " + str(
202 # first_minus_third))
203
204 # The color levels differ more than some threshold. Probably color image.
205 if first_minus_second > frames_color_difference_threshold \
206 or first_minus_third > frames_color_difference_threshold:
207 return 'Color'
208
209 # All three levels are the same, convert to 2D grayscale image and proceed.
210 else:
211 frame_grayscale = cvtColor(frame, COLOR_RGB2GRAY).astype(int32)
212
213 # Input frame is already grayscale.
214 elif len(frame.shape) == 2:
215 frame_grayscale = frame.astype(int32)
216
217 # Neither a color image nor grayscale.
218 else:
219 return 'None'
220
221 try:
222 height, width = frame_grayscale.shape
223 analysis_height = height - height % 2
224 analysis_width = width - width % 2
225
226 # Look for signs of a bayer pattern.
227 adjacent_pixel_diffs = np_sum(
228 abs(frame_grayscale[:, 0:analysis_width - 2] - frame_grayscale[:,
229 1:analysis_width - 1]))
230 apart_pixel_diffs = np_sum(
231 abs(frame_grayscale[:, 0:analysis_width - 2] - frame_grayscale[:, 2:analysis_width]))
232
233 # Pixels are more like the pixels next to them than they are like the pixels 2 pixel away.
234 # This indicates that there is no bayer pattern present
235 if apart_pixel_diffs > adjacent_pixel_diffs:
236 return 'Grayscale'
237
238 # Analyse noise characteristics of image to guess at positions of R, G and B in bayer pattern.
239 noise_level = ndarray((2, 2), dtype=float)
240 for y in range(2):
241 for x in range(2):
242 # Apply a five point (Poisson) stencil and sum over all points.
243 neighbors = (frame_grayscale[y:analysis_height - 6 + y:2,
244 2 + x:analysis_width - 4 + x:2] +
245 frame_grayscale[4 + y:analysis_height - 2 + y:2,
246 2 + x:analysis_width - 4 + x:2] +
247 frame_grayscale[2 + y:analysis_height - 4 + y:2,
248 x:analysis_width - 6 + x:2] +
249 frame_grayscale[2 + y:analysis_height - 4 + y:2,
250 4 + x:analysis_width - 2 + x:2]) / 4.
251 noise_level[y, x] = np_sum(
252 abs(frame_grayscale[2 + y:analysis_height - 4 + y:2,
253 2 + x:analysis_width - 4 + x:2] - neighbors))
254
255 # Normalize noise levels.
256 max_y, max_x = unravel_index(noise_level.argmax(), noise_level.shape)
257 max_noise_level = noise_level[max_y, max_x]
258 if max_noise_level > 0.:
259 noise_level = noise_level * (100. / max_noise_level)
260 # Zero noise - cannot detect bayer pattern.
261 else:
262 return 'Grayscale'
263
264 # The location of the maximum noise level is interpreted as the blue channel.
265 # It is in position (0, 0).
266 if (max_y, max_x) == (0, 0):
267 # The noise levels of the green pixels are too different for this to be a bayer pattern.
268 if abs(noise_level[0, 1] - noise_level[1, 0]) > frames_bayer_max_noise_diff_green:
269 return 'Grayscale'
270 # Noise levels of the other pixels are too close to the blue values for this to definitely
271 # be a bayer pattern.
272 if noise_level[0, 1] > frames_bayer_min_distance_from_blue or noise_level[
273 1, 0] > frames_bayer_min_distance_from_blue or noise_level[
274 1, 1] > frames_bayer_min_distance_from_blue:
275 return 'Grayscale'
276 # Bayer pattern "BGGR" found.
277 return 'Force Bayer BGGR'
278
279 # Case "GBRG":
280 elif (max_y, max_x) == (0, 1):
281 if abs(noise_level[0, 0] - noise_level[1, 1]) > frames_bayer_max_noise_diff_green:
282 return 'Grayscale'
283 if noise_level[0, 0] > frames_bayer_min_distance_from_blue or noise_level[
284 1, 0] > frames_bayer_min_distance_from_blue or noise_level[
285 1, 1] > frames_bayer_min_distance_from_blue:
286 return 'Grayscale'
287 # Bayer pattern "GBRG" found.
288 return 'Force Bayer GBRG'
289
290 # Case "GRBG":
291 elif (max_y, max_x) == (1, 0):
292 if abs(noise_level[0, 0] - noise_level[1, 1]) > frames_bayer_max_noise_diff_green:
293 return 'Grayscale'
294 if noise_level[0, 0] > frames_bayer_min_distance_from_blue or noise_level[
295 0, 1] > frames_bayer_min_distance_from_blue or noise_level[
296 1, 1] > frames_bayer_min_distance_from_blue:
297 return 'Grayscale'
298 # Bayer pattern "GRBG" found.
299 return 'Force Bayer GRBG'
300
301 # Case "RGGB"
302 elif (max_y, max_x) == (1, 1):
303 if abs(noise_level[0, 1] - noise_level[1, 0]) > frames_bayer_max_noise_diff_green:
304 return 'Grayscale'
305 if noise_level[0, 0] > frames_bayer_min_distance_from_blue or noise_level[
306 0, 1] > frames_bayer_min_distance_from_blue or noise_level[
307 1, 0] > frames_bayer_min_distance_from_blue:
308 return 'Grayscale'
309 # Bayer pattern "RGGB" found.
310 return 'Force Bayer RGGB'
311
312 # Theoretically this cannot be reached.
313 return 'None'
314
315 # If something bad has happened, return 'None'.
316 except Exception as e:
317 # print("An Exception occurred: " + str(e))
318 return 'None'
319
320 def detect_rgb_bgr(frame):
321 """
322 Given a color (3D) frame, find out if the channels are arranged as 'RGB' or 'BGR'. To this end,
323 the noise level of the first and third channels are compared. The channel with the highest noise
324 level is interpreted as the blue channel.
325
326 :param frame: Numpy array (3D) of type uint8 or uint16 containing the image data.
327 :return: Either 'RGB' or 'BGR', depending on whether the noise in the third or first channel is
328 highest. If an error occurs, 'None' is returned.
329 """
330
331 # Not a color (3D) frame:
332 if len(frame.shape) != 3:
333 return 'None'
334
335 try:
336 height, width = frame.shape[0:2]
337 analysis_height = height - height % 2
338 analysis_width = width - width % 2
339
340 # Analyse noise characteristics of image to guess at positions of R, G and B in bayer pattern.
341 frame_int32 = frame.astype(int32)
342 noise_level = [0., 0., 0.]
343 for channel in [0, 2]:
344 # Apply a five point (Poisson) stencil and sum over all points.
345 neighbors = (frame_int32[0:analysis_height - 2, 1:analysis_width - 1, channel] +
346 frame_int32[2:analysis_height, 1:analysis_width - 1, channel] +
347 frame_int32[1:analysis_height - 1, 0:analysis_width - 2, channel] +
348 frame_int32[1:analysis_height - 1, 2:analysis_width, channel]) / 4.
349 noise_level[channel] = np_sum(
350 abs(frame_int32[1:analysis_height - 1, 1:analysis_width - 1, channel] - neighbors))
351
352 # print("noise level 0:" + str(noise_level[0]) + ", noise level 2:" + str(noise_level[2]))
353 if noise_level[0] > noise_level[2]:
354 return 'BGR'
355 else:
356 return 'RGB'
357 except Exception as e:
358 # print("An Exception occurred: " + str(e))
359 return 'None'
360
361 class VideoReader(object):
362 """
363 The VideoReader deals with the import of frames from a video file. Frames can be read either
364 consecutively, or at an arbitrary frame index. Eventually, all common video types (such as .avi,
365 .mov, .mp4, .ser) should be supported.
366 """
367
368 def __init__(self, configuration):
369 """
370 Create the VideoReader object and initialize instance variables.
371
372 :param configuration: Configuration object with parameters
373 """
374
375 self.configuration = configuration
376 self.last_read = None
377 self.last_frame_read = None
378 self.frame_count = None
379 self.shape = None
380 self.color = None
381 self.convert_to_grayscale = False
382 self.dtype = None
383 self.SERFile = False
384 self.shift_pixels = 0
385 self.bayer_option_selected = None
386 self.bayer_pattern = None
387 self.BGR_input = None
388 self.warn_message = None
389
390 def sanity_check(self, file_path):
391 """
392 Performs a sanity check of input file.
393
394 :return: -
395 """
396
397 if not path.isfile(file_path):
398 raise IOError("File does not exist")
399 elif stat(file_path).st_size == 0:
400 raise IOError("File is empty")
401
402 def open(self, file_path, bayer_option_selected='Auto detect color',
403 SER_16bit_shift_correction=True):
404 """
405 Initialize the VideoReader object and return parameters with video metadata.
406 Throws an IOError if the video file format is not supported.
407
408 :param file_path: Full name of the video file.
409 :param bayer_option_selected: Bayer pattern, one out of: "Auto detect color", "Grayscale",
410 "RGB", "BGR", "Force Bayer RGGB", "Force Bayer GRBG",
411 "Force Bayer GBRG", "Force Bayer BGGR".
412 :param SER_16bit_shift_correction: If True and the frame type is 16bit, the video frames
413 are analyzed to find the number of unused high bits in
414 pixel data. In read operations data are shifted up by
415 this number of bits.
416 :return: (frame_count, color, dtype, shape) with
417 frame_count: Total number of frames in video.
418 color: True, if frames are in color; False otherwise.
419 dtype: Numpy type, either uint8 or uint16
420 shape: Tuple with the shape of a single frame; (num_px_y, num_px_x, 3) for color,
421 (num_px_y, num_px_x) for B/W.
422 shift_pixels: Number of unused (high) bits in pixel values. Frame data can be
423 left-shifted by this number without going into saturation.
424 """
425
426 # Do sanity check
427 self.sanity_check(file_path)
428
429 # Check, if file has SER extension
430 self.SERFile = path.splitext(file_path)[1].lower() == '.ser'
431
432 # Check if input file is SER file
433 if self.SERFile:
434 try:
435 # Create the VideoCapture object.
436 self.cap = ser_parser.SERParser(file_path, SER_16bit_shift_correction)
437 self.shift_pixels = self.cap.shift_pixels
438 self.warn_message = self.cap.warn_message
439
440 # Read the first frame.
441 self.last_frame_read = self.cap.read_frame_raw(0)
442
443 # Look up video metadata.
444 self.frame_count = self.cap.frame_count
445 self.color_in = self.cap.color
446 self.BGR_input = False
447 self.dtype = self.cap.PixelDepthPerPlane
448 # Set the bayer pattern. In automatic mode, use the pattern encoded in the SER
449 # file header.
450 if bayer_option_selected == 'Auto detect color':
451 self.bayer_pattern = self.cap.header['ColorIDDecoded']
452 else:
453 self.bayer_pattern = bayer_option_selected
454 except:
455 raise IOError("Error in reading first video frame")
456 else:
457 try:
458 # Create the VideoCapture object.
459 self.cap = VideoCapture(file_path)
460
461 # Read the first frame.
462 ret, self.last_frame_read = self.cap.read()
463 if not ret:
464 raise IOError("Error in reading first video frame")
465
466 # Look up video metadata. Set "BGR_input" to 'True' because OpenCV reads color
467 # images in BGR channel ordering. R and B channels have to be swapped because
468 # PSS works with RGB color internally.
469 self.frame_count = int(self.cap.get(CAP_PROP_FRAME_COUNT))
470 self.color_in = (len(self.last_frame_read.shape) == 3)
471 self.BGR_input = True
472 self.dtype = self.last_frame_read.dtype
473
474 # Set the bayer pattern.
475 if bayer_option_selected == 'Auto detect color':
476 # Look for a Bayer pattern in the 2D or 3D data.
477 bayer_pattern_computed = detect_bayer(self.last_frame_read,
478 self.configuration.frames_bayer_max_noise_diff_green,
479 self.configuration.frames_bayer_min_distance_from_blue,
480 self.configuration.frames_color_difference_threshold)
481 # If the image was classified as 'Color', test the ordering of color channels.
482 if bayer_pattern_computed == 'Color':
483 # Analyze first frame to detect ordering of color channels. Note that the
484 # frame was read by OpenCV in BGR mode. Channels will be swapt later.
485 rgb_order = detect_rgb_bgr(self.last_frame_read)
486 if rgb_order == 'BGR':
487 self.bayer_pattern = 'RGB'
488 # print("Color channel ordering 'RGB' detected")
489 elif rgb_order == 'RGB':
490 self.bayer_pattern = 'BGR'
491 # print("Color channel ordering 'BGR' detected")
492 else:
493 self.bayer_pattern = 'RGB'
494 # print("No color channel ordering detected, apply 'RGB'")
495 elif bayer_pattern_computed == 'Grayscale':
496 self.bayer_pattern = 'Grayscale'
497 # print("Image has been found to be grayscale")
498 elif bayer_pattern_computed == 'None':
499 if self.color_in:
500 self.bayer_pattern = 'RGB'
501 # print("No Bayer pattern detected, apply 'RGB' because 3D")
502 else:
503 self.bayer_pattern = 'Grayscale'
504 # print("No Bayer pattern detected, apply 'Grayscale' because 2D")
505 else:
506 self.bayer_pattern = bayer_pattern_computed
507 # print("Bayer pattern " + bayer_pattern_computed + " detected")
508
509 # The user has selected a debayering mode explicitly.
510 else:
511 # Leave the pattern unchanged.
512 self.bayer_pattern = bayer_option_selected
513 except:
514 raise IOError("Error in reading first video frame. Try to convert the video with "
515 "PIPP into some standard format")
516
517 # Assign "last_read"
518 self.last_read = 0
519
520 # Convert the first frame read into the desired output format and set the metadata.
521 self.last_frame_read = debayer_frame(self.last_frame_read,
522 debayer_pattern=self.bayer_pattern,
523 debayer_method=self.configuration.frames_debayering_method,
524 BGR_input=self.BGR_input)
525 self.shape = self.last_frame_read.shape
526 self.color = (len(self.shape) == 3)
527
528 # Return the metadata.
529 return self.frame_count, self.color, self.dtype, self.shape, self.shift_pixels
530
531 def read_frame(self, index=None):
532 """
533 Read a single frame from the video.
534
535 :param index: Frame index (optional). If no index is specified, the next frame is read.
536 :return: Numpy array containing the frame. For B/W, the shape is (num_px_y, num_px_x).
537 For a color video, it is (num_px_y, num_px_x, 3). The type is uint8 or uint16 for
538 8 or 16 bit resolution.
539 """
540
541 # Check the index.
542 if index is None:
543 # Consecutive reading. Just increment the frame pointer.
544 self.last_read += 1
545 elif index == self.last_read:
546 # An index is the same as at last call, just return the last frame.
547 return self.last_frame_read
548 else:
549 # If it is the next frame after the one read last time, for AVI videos the frame pointer
550 # does not have to be set. The read_frame method of the "ser_parser" module always does
551 # a seek operation.
552 if not self.SERFile and index != self.last_read + 1:
553 self.cap.set(CAP_PROP_POS_FRAMES, index)
554 self.last_read = index
555
556 # A new frame has to be read. First check if the index is not out of bounds.
557 if 0 <= self.last_read < self.frame_count:
558 try:
559 # Read the next frame.
560 if self.SERFile:
561 self.last_frame_read = self.cap.read_frame_raw(self.last_read)
562 else:
563 ret, self.last_frame_read = self.cap.read()
564 if not ret:
565 raise IOError("Error in reading video frame, index: {0}. Try to convert the video with "
566 "PIPP into some standard format".format(index))
567 except:
568 raise IOError("Error in reading video frame, index: {0}. Try to convert the video with "
569 "PIPP into some standard format".format(index))
570 else:
571 raise ArgumentError("Error in reading video frame, index {0} is out of bounds".format(index))
572
573 # Convert the frame read into the desired output format.
574 self.last_frame_read = debayer_frame(self.last_frame_read,
575 debayer_pattern=self.bayer_pattern,
576 debayer_method=self.configuration.frames_debayering_method,
577 BGR_input=self.BGR_input)
578
579 return self.last_frame_read
580
581 def close(self):
582 """
583 Close the VideoReader object.
584
585 :return:
586 """
587
588 self.cap.release()
589
590
591 class ImageReader(object):
592 """
593 The ImageReader deals with the import of frames from a list of single images. Frames can
594 be read either consecutively, or at an arbitrary frame index. It is assumed that the
595 lexicographic order of file names corresponds to their chronological order.
596 """
597
598 def __init__(self, configuration):
599 """
600 Create the ImageReader object and initialize instance variables.
601
602 :param configuration: Configuration object with parameters.
603 """
604
605 self.configuration = configuration
606 self.opened = False
607 self.just_opened = False
608 self.last_read = None
609 self.last_frame_read = None
610 self.frame_count = None
611 self.shape = None
612 self.color = None
613 self.convert_to_grayscale = False
614 self.dtype = None
615 self.bayer_pattern = None
616 self.shift_pixels = 0
617 self.warn_message = None
618
619 def open(self, file_path_list, bayer_option_selected='Auto detect color'):
620 """
621 Initialize the ImageReader object and return parameters with image metadata.
622
623 :param file_path_list: List with path names to the image files.
624 :param bayer_option_selected: Bayer pattern, one out of: "Auto detect color", "Grayscale",
625 "RGB", "BGR", "Force Bayer RGGB", "Force Bayer GRBG",
626 "Force Bayer GBRG", "Force Bayer BGGR".
627 This parameter is ignored for now.
628 :return: (frame_count, color, dtype, shape) with
629 frame_count: Total number of frames.
630 color: True, if frames are in color; False otherwise.
631 dtype: Numpy type, either uint8 or uint16
632 shape: Tuple with the shape of a single frame; (num_px_y, num_px_x, 3) for color,
633 (num_px_y, num_px_x) for B/W.
634 shift_pixels: Number of unused (high) bits in pixel values. Frame data can be
635 left-shifted by this number without going into saturation.
636 """
637
638 self.file_path_list = file_path_list
639 self.bayer_option_selected = bayer_option_selected
640 self.bayer_pattern = bayer_option_selected
641
642 try:
643 self.frame_count = len(self.file_path_list)
644
645 self.last_frame_read = Frames.read_image(self.file_path_list[0])
646
647 if self.convert_to_grayscale:
648 self.last_frame_read = cvtColor(self.last_frame_read, COLOR_RGB2GRAY)
649
650 # Look up metadata.
651 self.last_read = 0
652 self.shape = self.last_frame_read.shape
653 self.color = (len(self.shape) == 3)
654 self.dtype = self.last_frame_read.dtype
655 except Exception as ex:
656 raise IOError("Reading first frame: " + str(ex))
657
658 self.opened = True
659 self.just_opened = True
660
661 # Return the metadata.
662 return self.frame_count, self.color, self.dtype, self.shape, self.shift_pixels
663
664 def read_frame(self, index=None):
665 """
666 Read a single frame.
667
668 :param index: Frame index (optional). If no index is specified, the next frame is read.
669 At the first invocation, this is frame number 0.
670 :return: Numpy array containing the frame. For B/W, the shape is (num_px_y, num_px_x).
671 For a color video, it is (num_px_y, num_px_x, 3). The type is uint8 or uint16 for
672 8 or 16 bit resolution.
673 """
674
675 if not self.opened:
676 raise WrongOrderingError(
677 "Error: Attempt to read image file frame before opening ImageReader")
678
679 # Special case: first call after initialization.
680 if self.just_opened:
681 self.just_opened = False
682
683 # Frame 0 has been read during initialization. Not necessary to read it again.
684 if index is None or index == 0:
685 return self.last_frame_read
686
687 # General case: not the first call.
688 else:
689
690 # Consecutive reading. Just increment the frame index.
691 if index is None:
692 self.last_read += 1
693
694 # An index is specified explicitly. If it is the same as at last call, just return the
695 # last frame.
696 elif index == self.last_read:
697 return self.last_frame_read
698
699 # Some other frame was specified explicitly.
700 else:
701 self.last_read = index
702
703 # A new frame has to be read. First check if the index is not out of bounds.
704 if 0 <= self.last_read < self.frame_count:
705 try:
706 self.last_frame_read = Frames.read_image(self.file_path_list[self.last_read])
707 if self.convert_to_grayscale:
708 self.last_frame_read = cvtColor(self.last_frame_read, COLOR_RGB2GRAY)
709 except Exception as ex:
710 raise IOError("Reading image with index: " + str(index) + ", " + str(ex))
711 else:
712 raise ArgumentError("Reading image with index: " + str(index) +
713 ", index is out of bounds")
714
715 # Check if the metadata match.
716 shape = self.last_frame_read.shape
717 color = (len(shape) == 3)
718
719 # Check if all images have matching metadata.
720 if color != self.color:
721 raise ShapeError(
722 "Mixing grayscale and color images not supported, index: " + str(index))
723 elif shape != self.shape:
724 raise ShapeError("Images have different size, index: " + str(index))
725 elif self.last_frame_read.dtype != self.dtype:
726 raise TypeError("Images have different type, index: " + str(index))
727
728 return self.last_frame_read
729
730 def close(self):
731 """
732 Close the ImageReader object.
733
734 :return:
735 """
736
737 self.opened = False
738
739
740 class Calibration(QtCore.QObject):
741 """
742 This class performs the dark / flat calibration of frames. Master frames are created from
743 video files or image directories. Flats, darks and the stacking input must match in terms of
744 types, shapes and color modes.
745
746 """
747
748 report_calibration_error_signal = QtCore.pyqtSignal(str)
749
750 def __init__(self, configuration):
751 """
752 Initialize the object for dark / flat calibration.
753
754 :param configuration: Configuration object with parameters
755 """
756
757 super(Calibration, self).__init__()
758 self.configuration = configuration
759 self.warn_message = None
760 self.reset_masters()
761
762 def reset_masters(self):
763 """
764 De-activate master dark and flat frames.
765
766 :return: -
767 """
768
769 self.reset_master_dark()
770 self.reset_master_flat()
771
772 self.color = None
773 self.shape = None
774 self.dtype = None
775
776 def reset_master_dark(self):
777 """
778 De-activate a master dark frame.
779
780 :return: -
781 """
782
783 self.master_dark_frame = None
784 self.master_dark_frame_adapted = None
785 self.high_value = None
786 self.dark_color = None
787 self.dark_dtype = None
788 self.dark_shape = None
789
790 def reset_master_flat(self):
791 """
792 De-activate a master flat frame.
793
794 :return: -
795 """
796
797 self.master_flat_frame = None
798 self.inverse_master_flat_frame = None
799 self.flat_color = None
800 self.flat_dtype = None
801 self.flat_shape = None
802
803 def create_master(self, master_name, output_dtype=uint16):
804 """
805 Create a master frame by averaging a number of video frames or still images.
806
807 :param master_name: Path name of video file or image directory.
808 :param output_dtype: Data type of resulting master frame, one of:
809 - uint8 (high value = 255)
810 - uint16 (high value = 65535)
811 default: uint16
812 :return: Master frame
813 """
814
815 # Case video file:
816 if Path(master_name).is_file():
817 extension = Path(master_name).suffix
818 if extension.lower() in ('.avi', '.mov', '.mp4', '.ser'):
819 reader = VideoReader(self.configuration)
820 # Switch off dynamic range correction for 16bit SER files.
821 frame_count, input_color, input_dtype, input_shape, shift_pixels = reader.open(master_name,
822 bayer_option_selected=self.configuration.frames_debayering_default,
823 SER_16bit_shift_correction=False)
824 self.warn_message = reader.warn_message
825 self.configuration.hidden_parameters_current_dir = str(Path(master_name).parent)
826 else:
827 raise InternalError(
828 "Unsupported file type '" + extension + "' specified for master frame "
829 "construction")
830 # Case image directory:
831 elif Path(master_name).is_dir():
832 names = [path.join(master_name, name) for name in listdir(master_name)]
833 reader = ImageReader(self.configuration)
834 frame_count, input_color, input_dtype, input_shape, shift_pixels = reader.open(names,
835 bayer_option_selected=self.configuration.frames_debayering_default)
836 self.configuration.hidden_parameters_current_dir = str(master_name)
837 else:
838 raise InternalError("Cannot decide if input file is video or image directory")
839
840 # Sum all frames in a 64bit buffer.
841 master_frame_64 = zeros(input_shape, float64)
842 for index in range(frame_count):
843 master_frame_64 += reader.read_frame(index)
844
845 # Return the average frame in the format specified.
846 if output_dtype == input_dtype:
847 return (master_frame_64 / frame_count).astype(output_dtype)
848 elif output_dtype == uint8 and input_dtype == uint16:
849 factor = 1. / (frame_count * 256)
850 return (master_frame_64 * factor).astype(output_dtype)
851 elif output_dtype == uint16 and input_dtype == uint8:
852 factor = 256. / frame_count
853 return (master_frame_64 * factor).astype(output_dtype)
854 else:
855 raise ArgumentError("Cannot convert dtype from " + str(input_dtype) + " to " +
856 str(output_dtype))
857
858 def create_master_dark(self, dark_name, load_from_file=False):
859 """
860 Create a master dark image, or read it from a file.
861
862 :param dark_name: If a new master frame is to be created, path name of video file or image
863 directory. Otherwise the file name (Tiff or Fits) of the master frame.
864 :param load_from_file: True, if to be loaded from file. False, if to be created anew.
865 :return: -
866 """
867
868 # Reset a master dark frame if previously allocated.
869 self.reset_master_dark()
870
871 # Create the master frame or read it from a file.
872 if load_from_file:
873 try:
874 self.master_dark_frame = Frames.read_image(dark_name)
875 except Exception as e:
876 self.report_calibration_error_signal.emit("Error: " + str(e))
877 return
878
879 if self.master_dark_frame.dtype == uint8:
880 self.master_dark_frame = (self.master_dark_frame * 256).astype(uint16)
881 else:
882 self.master_dark_frame = self.create_master(dark_name, output_dtype=uint16)
883
884 self.shape = self.dark_shape = self.master_dark_frame.shape
885 self.color = self.dark_color = (len(self.dark_shape) == 3)
886 self.dark_dtype = self.master_dark_frame.dtype
887
888 # If a flat frame has been processed already, check for consistency. If master frames do not
889 # match, remove the master flat.
890 if self.inverse_master_flat_frame is not None:
891 if self.dark_color != self.flat_color or self.dark_shape != self.flat_shape:
892 self.reset_master_flat()
893 # Send a message to the main GUI indicating that a non-matching master flat is
894 # removed.
895 self.report_calibration_error_signal.emit(
896 "A non-matching master flat was de-activated")
897
898 def load_master_dark(self, dark_name):
899 """
900 Read a master dark frame from disk and initialize its metadata.
901
902 :param dark_name: Path name of master dark frame (type TIFF)
903 :return: -
904 """
905
906 self.create_master_dark(dark_name, load_from_file=True)
907
908 def create_master_flat(self, flat_name, load_from_file=False):
909 """
910 Create a master flat image, or read it from a file.
911
912 :param flat_name: If a new master frame is to be created, path name of video file or image
913 directory. Otherwise the file name (Tiff or Fits) of the master frame.
914 :param load_from_file: True, if to be loaded from file. False, if to be created anew.
915 :return: -
916 """
917
918 # Reset a master flat frame if previously allocated.
919 self.reset_master_flat()
920
921 # Create the master frame or read it from a file.
922 if load_from_file:
923 try:
924 self.master_flat_frame = Frames.read_image(flat_name)
925 except Exception as e:
926 self.report_calibration_error_signal.emit("Error: " + str(e))
927 return
928
929 if self.master_flat_frame.dtype == uint8:
930 self.master_flat_frame = (self.master_flat_frame * 256).astype(uint16)
931 else:
932 self.master_flat_frame = self.create_master(flat_name, output_dtype=uint16)
933
934 self.shape = self.flat_shape = self.master_flat_frame.shape
935 self.color = self.flat_color = (len(self.flat_shape) == 3)
936 self.flat_dtype = self.master_flat_frame.dtype
937
938 # If a dark frame has been processed already, check for consistency. If master frames do not
939 # match, remove the master dark.
940 if self.master_dark_frame is not None:
941 if self.dark_color != self.flat_color or self.dark_shape != self.flat_shape:
942 self.reset_master_dark()
943 # Send a message to the main GUI indicating that a non-matching master dark is
944 # removed.
945 self.report_calibration_error_signal.emit(
946 "A non-matching master dark was de-activated")
947
948 average_flat_frame = average(self.master_flat_frame).astype(uint16)
949
950 # If a new flat frame is to be constructed, apply a dark frame (if available).
951 if not load_from_file:
952 if self.master_dark_frame is not None:
953 # If there is a matching dark frame, use it to correct the flat frame. Avoid zeros
954 # in places where darks and flats are the same (hot pixels??).
955 self.master_flat_frame = where(self.master_flat_frame > self.master_dark_frame,
956 self.master_flat_frame - self.master_dark_frame,
957 average_flat_frame)
958
959 # Compute the inverse master flat (float32) so that its entries are close to one.
960 if average_flat_frame > 0:
961 self.inverse_master_flat_frame = (average_flat_frame / self.master_flat_frame).astype(
962 float32)
963 else:
964 self.reset_master_flat()
965 raise InternalError("Invalid input for flat frame computation")
966
967 def load_master_flat(self, flat_name):
968 """
969 Read a master flat frame from disk and initialize its metadata.
970
971 :param flat_name: Path name of master flat frame (type TIFF)
972 :return: -
973 """
974
975 try:
976 self.create_master_flat(flat_name, load_from_file=True)
977
978 # Send a signal to the main GUI and trigger error message printing there.
979 except Error as e:
980 self.report_calibration_error_signal.emit(
981 "Error in loading master flat: " + str(e) + ", flat correction de-activated")
982
983 def flats_darks_match(self, color, shape):
984 """
985 Check if the master flat / master dark match frame attributes.
986
987 :param color: True, if frames are in color; False otherwise.
988 :param shape: Tuple with the shape of a single frame; (num_px_y, num_px_x, 3) for color,
989 (num_px_y, num_px_x) for B/W.
990 :return: True, if attributes match; False otherwise.
991 """
992
993 return color == self.color and shape == self.shape
994
995 def adapt_dark_frame(self, frame_dtype, shift_pixels):
996 """
997 Adapt the type of the master dark frame to the type of frames to be corrected.
998
999 :param frame_dtype: Dtype of frames to be corrected. Either uint8 or uint16.
1000 :param shift_pixels: Number of unused (high) bits in pixel values. Frame data are
1001 left-shifted by this number so that they fill the full dynamic range.
1002 Since the dark frame is subtracted from all frames, it must be shifted
1003 by the same number of bits before being applied.
1004
1005 This correction is only relevant for 16bit SER videos.
1006 :return: -
1007 """
1008
1009 self.dtype = frame_dtype
1010
1011 if self.master_dark_frame is None:
1012 self.high_value = None
1013 self.master_dark_frame_adapted = None
1014 elif frame_dtype == uint8:
1015 self.high_value = 255
1016 self.master_dark_frame_adapted = (self.master_dark_frame / 256.).astype(uint8)
1017 elif frame_dtype == uint16:
1018 self.high_value = 65535
1019 if shift_pixels:
1020 self.master_dark_frame_adapted = self.master_dark_frame << shift_pixels
1021 else:
1022 self.master_dark_frame_adapted = self.master_dark_frame
1023
1024 def correct(self, frame):
1025 """
1026 Correct a stacking frame using a master dark and / or a master flat.
1027
1028 :param frame: Frame to be stacked.
1029 :return: Frame corrected for dark/flat, same type as input frame.
1030 """
1031
1032 # Case neither darks nor flats are available:
1033 if self.master_dark_frame_adapted is None and self.inverse_master_flat_frame is None:
1034 return frame
1035
1036 # Case only flats are available:
1037 elif self.master_dark_frame_adapted is None:
1038 return (frame * self.inverse_master_flat_frame).astype(self.dtype)
1039
1040 # Case only darks are available:
1041 elif self.inverse_master_flat_frame is None:
1042 return where(frame > self.master_dark_frame_adapted,
1043 frame - self.master_dark_frame_adapted, 0)
1044
1045 # Case both darks and flats are available:
1046 else:
1047 return clip(
1048 (frame - self.master_dark_frame_adapted) * self.inverse_master_flat_frame,
1049 0., self.high_value).astype(self.dtype)
1050
1051
1052 class Frames(object):
1053 """
1054 This object stores the image data of all frames. Four versions of the original frames are
1055 used throughout the data processing workflow. They are (re-)used in the folliwing phases:
1056 1. Original (color) frames, type: uint8 / uint16
1057 - Frame stacking ("stack_frames.stack_frames")
1058 2. Monochrome version of 1., type: uint8 / uint16
1059 - Computing the average frame (only average frame subset, "align_frames.average_frame")
1060 3. Gaussian blur added to 2., type: type: uint16
1061 - Aligning all frames ("align_frames.align_frames")
1062 - Frame stacking ("stack_frames.stack_frames")
1063 4. Down-sampled Laplacian of 3., type: uint8
1064 - Overall image ranking ("rank_frames.frame_score")
1065 - Ranking frames at alignment points("alignment_points.compute_frame_qualities")
1066
1067 Buffering at various levels is available. It is controlled with four flags set at object
1068 initialization time.
1069
1070 A complete PSS execution processes all "n" frames in four complete passes. Additionally,
1071 in module "align_frames" there are some extra accesses:
1072
1073 1. In "rank_frames.frame_score": Access to all "Laplacians of Gaussian" (frame 0 to n-1)
1074 In "align_frames.select_alignment_rect and .align_frames": Access to the Gaussian of the
1075 best frame.
1076 2. In "align_frames.align_frames": Access to all Gaussians (frame 0 to n-1)
1077 In "align_frames.average_frame": Access to the monochrome frames of the best images for
1078 averaging
1079 3. In "alignment_points.compute_frame_qualities": Access to all "Laplacians of Gaussian"
1080 (frame 0 to n-1)
1081 4. In "stack_frames.stack_frames": Access to all frames + Gaussians (frame 0 to n-1)
1082
1083 """
1084
1085 def __init__(self, configuration, names, type='video', bayer_option_selected="Auto detect color",
1086 calibration=None, progress_signal=None, buffering_level=2):
1087 """
1088 Initialize the Frame object, and read all images. Images can be stored in a video file or
1089 as single images in a directory.
1090
1091 :param configuration: Configuration object with parameters
1092 :param names: In case "video": name of the video file. In case "image": list of names for
1093 all images.
1094 :param type: Either "video" or "image".
1095 :param bayer_option_selected: Bayer pattern, one out of: "Auto detect color", "Grayscale",
1096 "RGB", "BGR", "Force Bayer RGGB", "Force Bayer GRBG",
1097 "Force Bayer GBRG", "Force Bayer BGGR".
1098 :param calibration: (Optional) calibration object for darks/flats correction.
1099 :param progress_signal: Either None (no progress signalling), or a signal with the signature
1100 (str, int) with the current activity (str) and the progress in
1101 percent (int).
1102 :param buffering_level: Level of buffering for original frames and image variants.
1103 """
1104
1105 self.configuration = configuration
1106 self.warn_message = None
1107 self.names = names
1108 self.calibration = calibration
1109 self.progress_signal = progress_signal
1110 self.type = type
1111 self.bayer_pattern = None
1112 self.bayer_option_selected = bayer_option_selected
1113 self.shift_pixels = None
1114
1115 self.buffer_original = None
1116 self.buffer_monochrome = None
1117 self.buffer_gaussian = None
1118 self.buffer_laplacian = None
1119 self.set_buffering(buffering_level)
1120
1121 # In non-buffered mode, the index of the image just read/computed is stored for re-use.
1122 self.original_available = None
1123 self.original_available_index = -1
1124 self.monochrome_available = None
1125 self.monochrome_available_index = -1
1126 self.gaussian_available = None
1127 self.gaussian_available_index = -1
1128 self.laplacian_available = None
1129 self.laplacian_available_index = None
1130
1131 # Set a flag that no monochrome image has been computed before.
1132 self.first_monochrome = True
1133
1134 # Initialize the list of original frames.
1135 self.frames_original = None
1136
1137 # Initialize index translation flag.
1138 self.index_translation_active = False
1139
1140 # Compute the scaling value for Laplacian computation.
1141 self.alpha = 1. / 256.
1142
1143 # Initialize and open the reader object.
1144 if self.type == 'image':
1145 self.reader = ImageReader(self.configuration)
1146 elif self.type == 'video':
1147 self.reader = VideoReader(self.configuration)
1148 else:
1149 raise TypeError("Image type " + self.type + " not supported")
1150
1151 self.number, self.color, self.dt0, self.shape, self.shift_pixels = self.reader.open(self.names,
1152 bayer_option_selected=self.bayer_option_selected)
1153 self.warn_message = self.reader.warn_message
1154
1155 # Look up the Bayer pattern the reader has identified.
1156 self.bayer_pattern = self.reader.bayer_pattern
1157
1158 # Set the depth value of all images to either 16 or 8 bits.
1159 if self.dt0 == 'uint16':
1160 self.depth = 16
1161 elif self.dt0 == 'uint8':
1162 self.depth = 8
1163 else:
1164 raise TypeError("Frame type " + str(self.dt0) + " not supported")
1165
1166 # Check if the darks / flats of the calibration object match the current reader.
1167 if self.calibration:
1168 self.calibration_matches = self.calibration.flats_darks_match(self.color, self.shape)
1169 # If there are matching darks or flats, adapt their type to the current frame type.
1170 if self.calibration_matches:
1171 self.calibration.adapt_dark_frame(self.dt0, self.shift_pixels)
1172 else:
1173 self.calibration_matches = False
1174
1175 # Initialize an index translation list which is used later to exclude a subset of indices
1176 # in the stacking workflow. Initially, all indices are included.
1177 self.number_original = self.number
1178 self.index_translation = [item for item in range(self.number_original)]
1179 self.index_included = [True] * self.number_original
1180
1181 # Initialize lists of monochrome frames (with and without Gaussian blur) and their
1182 # Laplacians.
1183 colors = ['red', 'green', 'blue', 'panchromatic']
1184 if self.configuration.frames_mono_channel in colors:
1185 self.color_index = colors.index(self.configuration.frames_mono_channel)
1186 else:
1187 raise ArgumentError("Invalid color selected for channel extraction")
1188 self.frames_monochrome = [None] * self.number_original
1189 self.frames_monochrome_blurred = [None] *self.number_original
1190 self.frames_monochrome_blurred_laplacian = [None] *self.number_original
1191 if self.configuration.frames_normalization:
1192 self.frames_average_brightness = [None] *self.number_original
1193 else:
1194 self.frames_average_brightness = None
1195 self.first_monochrome_index = None
1196 self.used_alignment_points = None
1197
1198 def set_buffering(self, buffering_level):
1199 """
1200 Set the buffering flags for original image data and its variants depending on the buffering
1201 level selected.
1202
1203 :param buffering_level: Level of buffering for image data and variants.
1204 :return: -
1205 """
1206
1207 self.buffer_original, self.buffer_monochrome, self.buffer_gaussian, self.buffer_laplacian =\
1208 Frames.decide_buffering(buffering_level)
1209
1210 @staticmethod
1211 def decide_buffering(buffering_level):
1212 """
1213 Decide on the objects to be buffered, depending on "buffering_level" configuration
1214 parameter. For each frame, four versions can be buffered or not:
1215 buffer_original: If "True", read the original frame data only once, otherwise
1216 read them again if required.
1217 buffer_monochrome: If "True", compute the monochrome image only once, otherwise
1218 compute it again if required.
1219 buffer_gaussian: If "True", compute the gaussian-blurred image only once, otherwise
1220 compute it again if required.
1221 buffer_laplacian: If "True", compute the "Laplacian of Gaussian" only once, otherwise
1222 compute it again if required.
1223
1224 :param buffering_level: Level of buffering for original frames and image variants.
1225 :return: Tuple with four booleans defining for each image version if it is to be buffered or
1226 not
1227
1228 """
1229
1230 buffer_original = False
1231 buffer_monochrome = False
1232 buffer_gaussian = False
1233 buffer_laplacian = False
1234
1235 if buffering_level > 0:
1236 buffer_laplacian = True
1237 if buffering_level > 1:
1238 buffer_gaussian = True
1239 if buffering_level > 2:
1240 buffer_original = True
1241 if buffering_level > 3:
1242 buffer_monochrome = True
1243
1244 return buffer_original, buffer_monochrome, buffer_gaussian, buffer_laplacian
1245
1246 def compute_required_buffer_size(self, buffering_level):
1247 """
1248 Compute the RAM required to store original images and their derivatives, and other objects
1249 which scale with the image size.
1250
1251 Additional to the original images and their derivatives, the following large objects are
1252 allocated during the workflow: mono color
1253 calibration.master_dark_frame: pixels * colors (float32) 4 12
1254 calibration.master_dark_frame_uint8: pixels * colors (uint8) 1 3
1255 calibration.master_dark_frame_uint16: pixels * colors (uint16) 2 6
1256 calibration.master_flat_frame: pixels * colors (float32) 4 12
1257 align_frames.mean_frame: image pixels (int32) 4 4
1258 align_frames.mean_frame_original: image pixels (int32) 4 4
1259 alignment_points, reference boxes: < 2 * image pixels (int32) 8 8
1260 alignment_points, stacking buffers: < 2 * image pixels * colors (float32) 8 24
1261 stack_frames.stacked_image_buffer: image pixels * colors (float32) 4 12
1262 stack_frames.number_single_frame_contributions: image pixels (int32) 4 4
1263 stack_frames.sum_single_frame_weights: image pixels (float32) 4 4
1264 stack_frames.averaged_background: image pixels * colors (float32) 4 12
1265 stack_frames.stacked_image: image pixels * colors (uint16) 2 6
1266 ---------
1267 Total (bytes / pixel): 53 111
1268 :param buffering_level: Buffering level parameter.
1269 :return: Number of required buffer space in bytes.
1270 """
1271
1272 # Compute the number of image pixels.
1273 number_pixel = self.shape[0] * self.shape[1]
1274
1275 # Compute the size of a monochrome image in bytes.
1276 image_size_monochrome_bytes = number_pixel * self.depth / 8
1277
1278 # Compute the size of an original image in bytes.
1279 if self.color:
1280 image_size_bytes = 3 * image_size_monochrome_bytes
1281 else:
1282 image_size_bytes = image_size_monochrome_bytes
1283
1284 # Compute the size of the monochrome images with Gaussian blur added in bytes.
1285 image_size_gaussian_bytes = number_pixel * 2
1286
1287 # Compute the size of a "Laplacian of Gaussian" in bytes. Remember that it is down-sampled.
1288 image_size_laplacian_bytes = number_pixel / \
1289 self.configuration.align_frames_sampling_stride ** 2
1290
1291 # Compute the buffer space per image, based on the buffering level.
1292 buffer_original, buffer_monochrome, buffer_gaussian, buffer_laplacian = \
1293 Frames.decide_buffering(buffering_level)
1294 buffer_per_image = 0
1295 if buffer_original:
1296 buffer_per_image += image_size_bytes
1297 if buffer_monochrome:
1298 buffer_per_image += image_size_monochrome_bytes
1299 if buffer_gaussian:
1300 buffer_per_image += image_size_gaussian_bytes
1301 if buffer_laplacian:
1302 buffer_per_image += image_size_laplacian_bytes
1303
1304 # Multiply with the total number of frames.
1305 buffer_for_all_images = buffer_per_image * self.number_original
1306
1307 # Compute the size of additional workspace objects allocated during the workflow. For the
1308 # details see the comment block at the beginning of this method.
1309 if self.color:
1310 buffer_additional_workspace = number_pixel * 111
1311 else:
1312 buffer_additional_workspace = number_pixel * 53
1313
1314 # Return the total buffer space required.
1315 return (buffer_for_all_images + buffer_additional_workspace) / 1e9
1316
1317 def frames(self, index):
1318 """
1319 Read or look up the original frame object with a given index.
1320
1321 :param index: Frame index
1322 :return: Frame with index "index".
1323 """
1324
1325 # print ("Accessing frame " + str(index))
1326
1327 # Check if the requested index is within bounds. Translate index, if necessary.
1328 if self.index_translation_active:
1329 if not 0 <= index < self.number:
1330 raise ArgumentError("Translated frame index " + str(index) + " is out of bounds")
1331 index_original = self.index_translation[index]
1332 else:
1333 if not 0 <= index < self.number_original:
1334 raise ArgumentError("Frame index " + str(index) + " is out of bounds")
1335 index_original = index
1336
1337 # If the original frames are to be buffered, read them in one go at the first call to this
1338 # method. In this case, a progress bar is displayed in the main GUI.
1339 if self.frames_original is None:
1340 if self.buffer_original:
1341 self.frames_original = []
1342 self.signal_step_size = max(int(self.number_original / 10), 1)
1343 for frame_index in range(self.number_original):
1344 # After every "signal_step_size"th frame, send a progress signal to the main GUI.
1345 if self.progress_signal is not None and frame_index % self.signal_step_size == 1:
1346 self.progress_signal.emit("Read all frames",
1347 int(round(10 * frame_index / self.number_original) * 10))
1348 # Read the next frame. If dark/flat correction is active, do the corrections.
1349 if self.calibration_matches:
1350 self.frames_original.append(self.calibration.correct(
1351 self.reader.read_frame(frame_index)))
1352 else:
1353 self.frames_original.append(self.reader.read_frame(frame_index))
1354
1355 self.reader.close()
1356 if self.progress_signal is not None:
1357 self.progress_signal.emit("Read all frames", 100)
1358
1359 # If original frames are not buffered, initialize an empty frame list, so frames can be
1360 # read later in non-consecutive order.
1361 else:
1362 self.frames_original = [None] * self.number_original
1363
1364 # The original frames are buffered. Just return the frame.
1365 if self.buffer_original:
1366 return self.frames_original[index_original]
1367
1368 # This frame has been cached. Just return it.
1369 if self.original_available_index == index_original:
1370 return self.original_available
1371
1372 # The frame has not been stored for re-use, read it. If dark/flat correction is active, do
1373 # the corrections.
1374 else:
1375 if self.calibration_matches:
1376 frame = self.calibration.correct(self.reader.read_frame(index_original))
1377 else:
1378 frame = self.reader.read_frame(index_original)
1379
1380 # Cache the frame just read.
1381 self.original_available = frame
1382 self.original_available_index = index_original
1383
1384 return frame
1385
1386 def frames_mono(self, index):
1387 """
1388 Look up or compute the monochrome version of the frame object with a given index.
1389
1390 :param index: Frame index
1391 :return: Monochrome frame with index "index".
1392 """
1393
1394 # Check if the requested index is within bounds. Translate index, if necessary.
1395 if self.index_translation_active:
1396 if not 0 <= index < self.number:
1397 raise ArgumentError("Translated frame index " + str(index) + " is out of bounds")
1398 index_original = self.index_translation[index]
1399 else:
1400 if not 0 <= index < self.number_original:
1401 raise ArgumentError("Frame index " + str(index) + " is out of bounds")
1402 index_original = index
1403
1404 # print("Accessing frame monochrome " + str(index))
1405 # The monochrome frames are buffered, and this frame has been stored before. Just return
1406 # the frame.
1407 if self.frames_monochrome[index_original] is not None:
1408 return self.frames_monochrome[index_original]
1409
1410 # If the monochrome frame is cached, just return it.
1411 if self.monochrome_available_index == index_original:
1412 return self.monochrome_available
1413
1414 # The frame has not been stored for re-use, compute it.
1415 else:
1416
1417 # Get the original frame. If it is not cached, this involves I/O.
1418 frame_original = self.frames(index)
1419
1420 # If frames are in color mode produce a B/W version.
1421 if self.color:
1422 if self.color_index == 3:
1423 frame_mono = cvtColor(frame_original, COLOR_RGB2GRAY)
1424 else:
1425 frame_mono = frame_original[:, :, self.color_index]
1426 # Frames are in B/W mode already
1427 else:
1428 frame_mono = frame_original
1429
1430 # Normalize the overall frame brightness. The first monochrome frame for which this
1431 # method is invoked is taken as the reference. The average brightness of all other
1432 # monochrome frames is adjusted to match the brightness of the referenence.
1433 if self.configuration.frames_normalization:
1434 frame_type = frame_mono.dtype
1435 if self.first_monochrome:
1436 if frame_type == uint8:
1437 self.normalization_lower_threshold = \
1438 self.configuration.frames_normalization_threshold
1439 self.normalization_upper_threshold = 255
1440 else:
1441 self.normalization_lower_threshold = \
1442 self.configuration.frames_normalization_threshold * 256
1443 self.normalization_upper_threshold = 255
1444
1445 self.frames_average_brightness[index_original] = cv_mean(
1446 threshold(frame_mono, self.normalization_lower_threshold,
1447 self.normalization_upper_threshold,
1448 THRESH_TOZERO)[1])[0] + 1.e-10
1449 # Keep the index of the first monochrome frame as the reference index.
1450 self.first_monochrome_index = index_original
1451 self.first_monochrome = False
1452 # Not the first monochrome frame. Adjust brightness to match the reference.
1453 else:
1454 self.frames_average_brightness[index_original] = cv_mean(
1455 threshold(frame_mono, self.normalization_lower_threshold,
1456 self.normalization_upper_threshold,
1457 THRESH_TOZERO)[1])[0] + 1.e-10
1458
1459 # If the monochrome frames are buffered, store it at the current index.
1460 if self.buffer_monochrome:
1461 self.frames_monochrome[index_original] = frame_mono
1462
1463 # If frames are not buffered, cache the current frame.
1464 else:
1465 self.monochrome_available_index = index_original
1466 self.monochrome_available = frame_mono
1467
1468 return frame_mono
1469
1470 def frames_mono_blurred(self, index):
1471 """
1472 Look up a Gaussian-blurred frame object with a given index.
1473
1474 :param index: Frame index
1475 :return: Gaussian-blurred frame with index "index".
1476 """
1477
1478 # Check if the requested index is within bounds. Translate index, if necessary.
1479 if self.index_translation_active:
1480 if not 0 <= index < self.number:
1481 raise ArgumentError("Translated frame index " + str(index) + " is out of bounds")
1482 index_original = self.index_translation[index]
1483 else:
1484 if not 0 <= index < self.number_original:
1485 raise ArgumentError("Frame index " + str(index) + " is out of bounds")
1486 index_original = index
1487
1488 # print("Accessing frame with Gaussian blur " + str(index))
1489 # The blurred frames are buffered, and this frame has been stored before. Just return
1490 # the frame.
1491 if self.frames_monochrome_blurred[index_original] is not None:
1492 return self.frames_monochrome_blurred[index_original]
1493
1494 # If the blurred frame is cached, just return it.
1495 if self.gaussian_available_index == index_original:
1496 return self.gaussian_available
1497
1498 # The frame has not been stored for re-use, compute it.
1499 else:
1500
1501 # Get the monochrome frame. If it is not cached, this involves I/O.
1502 frame_mono = self.frames_mono(index)
1503
1504 # If the mono image is 8bit, interpolate it to 16bit.
1505 if frame_mono.dtype == uint8:
1506 frame_mono = frame_mono.astype(uint16) * 256
1507
1508 # Compute a version of the frame with Gaussian blur added.
1509 frame_monochrome_blurred = GaussianBlur(frame_mono,
1510 (self.configuration.frames_gauss_width,
1511 self.configuration.frames_gauss_width), 0)
1512
1513 # If the blurred frames are buffered, store the current frame at the current index.
1514 if self.buffer_gaussian:
1515 self.frames_monochrome_blurred[index_original] = frame_monochrome_blurred
1516
1517 # If frames are not buffered, cache the current frame.
1518 else:
1519 self.gaussian_available_index = index_original
1520 self.gaussian_available = frame_monochrome_blurred
1521
1522 return frame_monochrome_blurred
1523
1524 def frames_mono_blurred_laplacian(self, index):
1525 """
1526 Look up a Laplacian-of-Gaussian of a frame object with a given index.
1527
1528 :param index: Frame index
1529 :return: LoG of a frame with index "index".
1530 """
1531
1532 # Check if the requested index is within bounds. Translate index, if necessary.
1533 if self.index_translation_active:
1534 if not 0 <= index < self.number:
1535 raise ArgumentError("Translated frame index " + str(index) + " is out of bounds")
1536 index_original = self.index_translation[index]
1537 else:
1538 if not 0 <= index < self.number_original:
1539 raise ArgumentError("Frame index " + str(index) + " is out of bounds")
1540 index_original = index
1541
1542 # print("Accessing LoG number " + str(index))
1543 # The LoG frames are buffered, and this frame has been stored before. Just return the frame.
1544 if self.frames_monochrome_blurred_laplacian[index_original] is not None:
1545 return self.frames_monochrome_blurred_laplacian[index_original]
1546
1547 # If the blurred frame is cached, just return it.
1548 if self.laplacian_available_index == index_original:
1549 return self.laplacian_available
1550
1551 # The frame has not been stored for re-use, compute it.
1552 else:
1553
1554 # Get the monochrome frame. If it is not cached, this involves I/O.
1555 frame_monochrome_blurred = self.frames_mono_blurred(index)
1556
1557 # Compute a version of the frame with Gaussian blur added.
1558 frame_monochrome_laplacian = convertScaleAbs(Laplacian(
1559 frame_monochrome_blurred[::self.configuration.align_frames_sampling_stride,
1560 ::self.configuration.align_frames_sampling_stride], CV_32F),
1561 alpha=self.alpha)
1562
1563 # If the blurred frames are buffered, store the current frame at the current index.
1564 if self.buffer_laplacian:
1565 self.frames_monochrome_blurred_laplacian[index_original] = frame_monochrome_laplacian
1566
1567 # If frames are not buffered, cache the current frame.
1568 else:
1569 self.laplacian_available_index = index_original
1570 self.laplacian_available = frame_monochrome_laplacian
1571
1572 return frame_monochrome_laplacian
1573
1574 def average_brightness(self, index):
1575 """
1576 Look up the average brightness of a frame with given index.
1577
1578 :param index: Frame index
1579 :return: average brightness of the requested frame
1580 """
1581
1582 # Check if the requested index is within bounds. Translate index, if necessary.
1583 if self.index_translation_active:
1584 if not 0 <= index < self.number:
1585 raise ArgumentError("Translated frame index " + str(index) + " is out of bounds")
1586 index_original = self.index_translation[index]
1587 else:
1588 if not 0 <= index < self.number_original:
1589 raise ArgumentError("Frame index " + str(index) + " is out of bounds")
1590 index_original = index
1591
1592 ab = self.frames_average_brightness[index_original]
1593 if ab:
1594 return ab
1595 else:
1596 raise InternalError("Accessing average frame brightness before computing it, frame: " +
1597 str(index_original))
1598
1599 def set_index_translation(self):
1600 """
1601 Set the index translation table. The list "self.index_included" for every original frame
1602 index specifies if the frame is included in the processing workflow (True) or not (False).
1603 Based on this list, a translation table "self.index_translation" is constructed. For the
1604 reduced set of frames which take part in the processing workflow it contains the original
1605 frame indices.
1606
1607 :return: -
1608 """
1609
1610 self.index_translation = []
1611 for index in range(self.number_original):
1612 if self.index_included[index]:
1613 self.index_translation.append(index)
1614
1615 # Set the number of frames which will take part in the processing workflow.
1616 self.number = len(self.index_translation)
1617
1618 # Set the index translation flag, so that in future frame lookups the translation table
1619 # will be used.
1620 self.index_translation_active = True
1621
1622 def reset_index_translation(self):
1623 """
1624 Reset the index translation table, and de-activate index translation. Keep the list of
1625 included / excluded frames, so that it can be the start point for another index translation.
1626
1627 :return: -
1628 """
1629
1630 self.number = self.number_original
1631 self.index_translation = None
1632 self.index_translation_active = False
1633
1634 def reset_alignment_point_lists(self):
1635 """
1636 Every frame keeps a list with the alignment points for which this frame is among the
1637 sharpest ones (so it is used in stacking). Reset this list for all frames.
1638
1639 :return: -
1640 """
1641
1642 # For every frame initialize the list with used alignment points.
1643 self.used_alignment_points = [[] for index in range(self.number)]
1644
1645 @staticmethod
1646 def save_image(filename, image, color=False, avoid_overwriting=True,
1647 header="PlanetarySystemStacker"):
1648 """
1649 Save an image to a file. If "avoid_overwriting" is set to False, images can have either
1650 ".png", ".tiff" or ".fits" format.
1651
1652 :param filename: Name of the file where the image is to be written
1653 :param image: ndarray object containing the image data
1654 :param color: If True, a three channel RGB image is to be saved. Otherwise, it is assumed
1655 that the image is monochrome.
1656 :param avoid_overwriting: If True, append a string to the input name if necessary so that
1657 it does not match any existing file. If False, overwrite
1658 an existing file.
1659 :param header: String with information on the PSS version being used (optional).
1660 :return: -
1661 """
1662
1663 # Handle the special case of .fits files first.
1664 if Path(filename).suffix == '.fits':
1665 # Flip image horizontally to preserve orientation
1666 image = flip(image, 0)
1667 if color:
1668 image = moveaxis(image, -1, 0)
1669 hdu = fits.PrimaryHDU(image)
1670 hdu.header['CREATOR'] = header
1671 hdu.writeto(filename, overwrite=True)
1672
1673 # Not a .fits file, the name can either point to a file or a directory, or be new.
1674 else:
1675 if Path(filename).is_dir():
1676 # If a directory with the given name already exists, append the word "_file".
1677 filename += '_file'
1678 if avoid_overwriting:
1679 while True:
1680 if not Path(filename + '.png').exists():
1681 break
1682 filename += '_file'
1683 filename += '.png'
1684 else:
1685 filename += '.png'
1686 if Path(filename).is_file():
1687 remove(filename)
1688
1689 # It is a file.
1690 elif Path(filename).is_file():
1691 # If overwriting is to be avoided, try to append "_copy" to its basename.
1692 # If it still exists, repeat.
1693 if avoid_overwriting:
1694 suffix = Path(filename).suffix
1695 while True:
1696 p = Path(filename)
1697 filename = Path.joinpath(p.parents[0], p.stem + '_copy' + suffix)
1698 if not Path(filename).exists():
1699 break
1700 # File may be overwritten. Delete it first.
1701 else:
1702 remove(filename)
1703
1704 # It is a new name. If it does not have a file suffix, add the default '.png'.
1705 else:
1706 # If the file name is new and has no suffix, add ".png".
1707 if not Path(filename).suffix:
1708 filename += '.png'
1709
1710 if Path(filename).suffix not in ['.tiff', '.png']:
1711 raise TypeError("Attempt to write image format other than '.tiff' or '.png'")
1712
1713 # Write the image to the file. Before writing, convert the internal RGB representation
1714 # into the BGR representation assumed by OpenCV.
1715 if color:
1716 imwrite(str(filename), cvtColor(image, COLOR_RGB2BGR))
1717 else:
1718 imwrite(str(filename), image)
1719
1720 @staticmethod
1721 def read_image(filename):
1722 """
1723 Read an image (in tiff, fits, png or jpg format) from a file.
1724
1725 :param filename: Path name of the input image.
1726 :return: RGB or monochrome image.
1727 """
1728
1729 name, suffix = splitext(filename)
1730
1731 # Make sure files with extensions written in large print can be read as well.
1732 suffix = suffix.lower()
1733
1734 # Case FITS format:
1735 if suffix in ('.fit', '.fits'):
1736 image = fits.getdata(filename)
1737
1738 # FITS output file from AS3 is 16bit depth file, even though BITPIX
1739 # has been set to "-32", which would suggest "numpy.float32"
1740 # https://docs.astropy.org/en/stable/io/fits/usage/image.html
1741 # To process this data in PSS, do "round()" and convert numpy array to "np.uint16"
1742 if image.dtype == '>f4':
1743 image = image.round().astype(uint16)
1744
1745 # If color image, move axis to be able to process the content
1746 if len(image.shape) == 3:
1747 image = moveaxis(image, 0, -1).copy()
1748
1749 # Flip image horizontally to recover original orientation
1750 image = flip(image, 0)
1751
1752 # Case other supported image formats:
1753 elif suffix in ('.tiff', '.tif', '.png', '.jpg'):
1754 input_image = imread(filename, IMREAD_UNCHANGED)
1755 if input_image is None:
1756 raise IOError("Cannot read image file. Possible cause: Path contains non-ascii characters")
1757
1758 # If color image, convert to RGB mode.
1759 if len(input_image.shape) == 3:
1760 image = cvtColor(input_image, COLOR_BGR2RGB)
1761 else:
1762 image = input_image
1763
1764 else:
1765 raise TypeError("Attempt to read image format other than 'tiff', 'tif',"
1766 " '.png', '.jpg' or 'fit', 'fits'")
1767
1768 return image
1769
1770 def access_pattern(frames_object, average_frame_percent):
1771 """
1772 Simulate the access pattern of PSS to frame data, without any other activity in between. Return
1773 the overall time.
1774
1775 :param frames_object: Frames object to access frames.
1776 :param average_frame_percent: Percentage of frames for average image computation.
1777 :return: Total time in seconds.
1778 """
1779
1780 number = frames_object.number
1781 average_frame_number = max(
1782 ceil(number * average_frame_percent / 100.), 1)
1783 start = time()
1784
1785 for index in range(number):
1786 frames_object.frames_mono_blurred_laplacian(index)
1787
1788 frames_object.frames_mono_blurred(number - 1)
1789 frames_object.frames_mono_blurred(number - 1)
1790
1791 for index in range(number):
1792 frames_object.frames_mono_blurred(index)
1793
1794 for index in range(average_frame_number):
1795 frames_object.frames_mono(index)
1796
1797 for index in range(number):
1798 frames_object.frames_mono_blurred_laplacian(index)
1799
1800 for index in range(number):
1801 frames_object.frames(index)
1802 frames_object.frames_mono_blurred(index)
1803
1804 return time() - start
1805
1806
1807 def access_pattern_simple(frames_object, average_frame_percent):
1808 """
1809 Simulate the access pattern of PSS to frame data, without any other activity in between. Return
1810 the overall time.
1811
1812 :param frames_object: Frames object to access frames.
1813 :param average_frame_percent: Percentage of frames for average image computation.
1814 :return: Total time in seconds.
1815 """
1816
1817 number = frames.number
1818 start = time()
1819
1820 for rep_cnt in range(5):
1821 for index in range(number):
1822 frames_object.frames_mono_blurred(index)
1823
1824 return time() - start
1825
1826
1827 if __name__ == "__main__":
1828
1829 # Images can either be extracted from a video file or a batch of single photographs. Select
1830 # the example for the test run.
1831 type = 'video'
1832 version = 'frames'
1833 buffering_level = 4
1834
1835 name_flats = None
1836 name_darks = None
1837 if type == 'image':
1838 # names = glob('Images/2012_*.tif')
1839 # names = glob('D:\SW-Development\Python\PlanetarySystemStacker\Examples\Moon_2011-04-10\South\*.TIF')
1840 names = glob(
•1841 r'D:\SW-Development\Python\PlanetarySystemStacker\Examples\Moon_2019-01-20\Images\*.TIF')
1842 else:
1843 # names = 'Videos/another_short_video.avi'
1844 # names = 'Videos/Moon_Tile-024_043939.avi'
1845 # names = r'E:\SW-Development\Python\PlanetarySystemStacker\Examples\SER_Chris-Garry' \
1846 # r'\SER_RGGB_16bit_LittleEndian_397_397.ser'
1847 # names = r'E:\SW-Development\Python\PlanetarySystemStacker\Examples\SER_Chris-Garry' \
1848 # r'\SER_GRAYSCALED_16bit_LittleEndian_397_397.ser'
1849 # names = r'E:\SW-Development\Python\PlanetarySystemStacker\Examples\SER_Chris-Garry' \
1850 # r'\SER_GRAYSCALED_12bit_BigEndian_352_400.ser'
1851 names = r'D:\SW-Development\Python\PlanetarySystemStacker\Examples\Jupiter_Richard\2020-07-29-2145_3-L-Jupiter_ALTAIRGP224C.ser'
1852 # name_flats = 'D:\SW-Development\Python\PlanetarySystemStacker\Examples\Darks_and_Flats\ASI120MM-S_Flat.avi'
1853 # name_darks = 'D:\SW-Development\Python\PlanetarySystemStacker\Examples\Darks_and_Flats\ASI120MM-S_Dark.avi'
1854
1855 # Get configuration parameters.
1856 configuration = Configuration()
1857 configuration.initialize_configuration()
1858
1859 # Initialize the Dark / Flat correction.
1860 if name_darks or name_flats:
1861 calibration = Calibration(configuration)
1862 else:
1863 calibration = None
1864
1865 # Create the master dark if requested.
1866 if name_darks:
1867 calibration.create_master_dark(name_darks)
1868 print("Master dark created, shape: " + str(calibration.master_dark_frame.shape))
1869 dark_min = np_min(calibration.master_dark_frame)
1870 dark_max = np_max(calibration.master_dark_frame)
1871 print("Dark min: " + str(dark_min) + ", Dark max: " + str(dark_max))
1872
1873 # Create the master flat if requested.
1874 if name_flats:
1875 calibration.create_master_flat(name_flats)
1876 print("Master flat created, shape: " + str(calibration.inverse_master_flat_frame.shape))
1877 flat_min = np_min(calibration.inverse_master_flat_frame)
1878 flat_max = np_max(calibration.inverse_master_flat_frame)
1879 print("Flat min: " + str(flat_min) + ", Flat max: " + str(flat_max))
1880
1881 start = time()
1882 if version == 'frames':
1883 try:
1884 frames = Frames(configuration, names, type=type, calibration=calibration,
1885 buffering_level=buffering_level)
1886 except Error as e:
1887 print("Error: " + e.message)
1888 exit()
1889 else:
1890 try:
1891 frames = FramesOld(configuration, names, type=type)
1892 frames.add_monochrome(configuration.frames_mono_channel)
1893 except Error as e:
1894 print("Error: " + e.message)
1895 exit()
1896 initialization_time = time() - start
1897
1898 print("Number of images read: " + str(frames.number))
1899 print("Image shape: " + str(frames.shape))
1900
1901 # total_access_time = access_pattern_simple(frames,
1902 # configuration.align_frames_average_frame_percent)
1903 total_access_time = access_pattern(frames, configuration.align_frames_average_frame_percent)
1904
1905 print("\nInitialization time: {0:7.3f}, frame accesses and variant computations: {1:7.3f},"
1906 " total: {2:7.3f} (seconds)".format(initialization_time, total_access_time,
1907 initialization_time + total_access_time))
1908
1909 frame = frames.frames(1776)
1910 print("Image type: " + str(frame.dtype))
1911
1912 # Check the OpenCV BGR and Matplotlibs RGB color orders
1913 import matplotlib
1914 matplotlib.use('Agg')
1915 import matplotlib.pyplot as plt
1916 if frames.color:
1917 plt.imshow(frame)
1918 else:
1919 plt.imshow(frame, cmap='gray')
1920 plt.show()
1921
1922 Frames.save_image('frame_1776.png', frame, color=True)