Debian Codegraph @

planetary_system_stacker/Test_programs/brightness_normalization.py

raw symbols SCIP
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 os import path, remove
24 from os.path import splitext
25 from pathlib import Path
26
27 from astropy.io import fits
28 from cv2 import imread, cvtColor, COLOR_RGB2GRAY, COLOR_BGR2RGB, THRESH_TOZERO, threshold, \
29 GaussianBlur, Laplacian, CV_32F, COLOR_RGB2BGR, imwrite, convertScaleAbs, IMREAD_UNCHANGED, flip
30 from cv2 import mean as cv_mean
31 from numpy import uint8, uint16, clip, moveaxis
32
33 from configuration import Configuration
34 from exceptions import TypeError, ArgumentError, Error
35 from frames import ImageReader, VideoReader
36 from rank_frames import RankFrames
37 from timer import timer
38
39
40 class Frames(object):
41 """
42 This object stores the image data of all frames. Four versions of the original frames are
43 used throughout the data processing workflow. They are (re-)used in the folliwing phases:
44 1. Original (color) frames, type: uint8 / uint16
45 - Frame stacking ("stack_frames.stack_frames")
46 2. Monochrome version of 1., type: uint8 / uint16
47 - Computing the average frame (only average frame subset, "align_frames.average_frame")
48 3. Gaussian blur added to 2., type: type: uint16
49 - Aligning all frames ("align_frames.align_frames")
50 - Frame stacking ("stack_frames.stack_frames")
51 4. Down-sampled Laplacian of 3., type: uint8
52 - Overall image ranking ("rank_frames.frame_score")
53 - Ranking frames at alignment points("alignment_points.compute_frame_qualities")
54
55 Buffering at various levels is available. It is controlled with four flags set at object
56 initialization time.
57
58 A complete PSS execution processes all "n" frames in four complete passes. Additionally,
59 in module "align_frames" there are some extra accesses:
60
61 1. In "rank_frames.frame_score": Access to all "Laplacians of Gaussian" (frame 0 to n-1)
62 In "align_frames.select_alignment_rect and .align_frames": Access to the Gaussian of the
63 best frame.
64 2. In "align_frames.align_frames": Access to all Gaussians (frame 0 to n-1)
65 In "align_frames.average_frame": Access to the monochrome frames of the best images for
66 averaging
67 3. In "alignment_points.compute_frame_qualities": Access to all "Laplacians of Gaussian"
68 (frame 0 to n-1)
69 4. In "stack_frames.stack_frames": Access to all frames + Gaussians (frame 0 to n-1)
70
71 """
72
73 @staticmethod
74 def set_buffering(buffering_level):
75 """
76 Decide on the objects to be buffered, depending on "buffering_level" configuration
77 parameter.
78
79 :param buffering_level: Buffering level parameter as set in configuration.
80 :return: Tuple of four booleans:
81 buffer_original: Keep all original frames in buffer.
82 buffer_monochrome: Keep the monochrome version of all original frames in buffer.
83 buffer_gaussian: Keep the monochrome version with Gaussian blur added of all
84 frames in buffer.
85 buffer_laplacian: Keep the Laplacian of Gaussian (LoG) of the monochrome version of
86 all frames in buffer.
87 """
88
89 buffer_original = False
90 buffer_monochrome = False
91 buffer_gaussian = False
92 buffer_laplacian = False
93
94 if buffering_level > 0:
95 buffer_laplacian = True
96 if buffering_level > 1:
97 buffer_gaussian = True
98 if buffering_level > 2:
99 buffer_original = True
100 if buffering_level > 3:
101 buffer_monochrome = True
102
103 return buffer_original, buffer_monochrome, buffer_gaussian, buffer_laplacian
104
105 def __init__(self, configuration, names, type='video', bayer_option_selected="Auto detect color",
106 calibration=None, progress_signal=None,
107 buffer_original=True, buffer_monochrome=False, buffer_gaussian=True,
108 buffer_laplacian=True):
109 """
110 Initialize the Frame object, and read all images. Images can be stored in a video file or
111 as single images in a directory.
112
113 :param configuration: Configuration object with parameters
114 :param names: In case "video": name of the video file. In case "image": list of names for
115 all images.
116 :param type: Either "video" or "image".
117 :param bayer_option_selected: Bayer pattern, one out of: "Auto detect color", "Grayscale",
118 "RGB", "BGR", "Force Bayer RGGB", "Force Bayer GRBG",
119 "Force Bayer GBRG", "Force Bayer BGGR".
120 :param calibration: (Optional) calibration object for darks/flats correction.
121 :param progress_signal: Either None (no progress signalling), or a signal with the signature
122 (str, int) with the current activity (str) and the progress in
123 percent (int).
124 :param buffer_original: If "True", read the original frame data only once, otherwise
125 read them again if required.
126 :param buffer_monochrome: If "True", compute the monochrome image only once, otherwise
127 compute it again if required. This may include re-reading the
128 original image data.
129 :param buffer_gaussian: If "True", compute the gaussian-blurred image only once, otherwise
130 compute it again if required. This may include re-reading the
131 original image data.
132 :param buffer_laplacian: If "True", compute the "Laplacian of Gaussian" only once, otherwise
133 compute it again if required. This may include re-reading the
134 original image data.
135 """
136
137 self.configuration = configuration
138 self.names = names
139 self.calibration = calibration
140 self.progress_signal = progress_signal
141 self.type = type
142 self.bayer_pattern = None
143 self.bayer_option_selected = bayer_option_selected
144
145 self.buffer_original = buffer_original
146 self.buffer_monochrome = buffer_monochrome
147 self.buffer_gaussian = buffer_gaussian
148 self.buffer_laplacian = buffer_laplacian
149
150 # In non-buffered mode, the index of the image just read/computed is stored for re-use.
151 self.original_available = None
152 self.original_available_index = -1
153 self.monochrome_available = None
154 self.monochrome_available_index = -1
155 self.gaussian_available = None
156 self.gaussian_available_index = -1
157 self.laplacian_available = None
158 self.laplacian_available_index = None
159
160 # Set a flag that no monochrome image has been computed before.
161 self.first_monochrome = True
162
163 # Initialize the list of original frames.
164 self.frames_original = None
165
166 # Compute the scaling value for Laplacian computation.
167 self.alpha = 1. / 256.
168
169 # Initialize and open the reader object.
170 if self.type == 'image':
171 self.reader = ImageReader(self.configuration)
172 elif self.type == 'video':
173 self.reader = VideoReader(self.configuration)
174 else:
175 raise TypeError("Image type " + self.type + " not supported")
176
177 self.number, self.color, self.dt0, self.shape, self.shift_pixels = self.reader.open(self.names,
178 bayer_option_selected=self.bayer_option_selected)
179
180 # Look up the Bayer pattern the reader has identified.
181 self.bayer_pattern = self.reader.bayer_pattern
182
183 # Set the depth value of all images to either 16 or 8 bits.
184 if self.dt0 == 'uint16':
185 self.depth = 16
186 elif self.dt0 == 'uint8':
187 self.depth = 8
188 else:
189 raise TypeError("Frame type " + str(self.dt0) + " not supported")
190
191 # Check if the darks / flats of the calibration object match the current reader.
192 if self.calibration:
193 self.calibration_matches = self.calibration.flats_darks_match(self.color, self.shape)
194 # If there are matching darks or flats, adapt their type to the current frame type.
195 if self.calibration_matches:
196 self.calibration.adapt_dark_frame(self.dt0, self.shift_pixels)
197 else:
198 self.calibration_matches = False
199
200 # Initialize lists of monochrome frames (with and without Gaussian blur) and their
201 # Laplacians.
202 colors = ['red', 'green', 'blue', 'panchromatic']
203 if self.configuration.frames_mono_channel in colors:
204 self.color_index = colors.index(self.configuration.frames_mono_channel)
205 else:
206 raise ArgumentError("Invalid color selected for channel extraction")
207 self.frames_monochrome = [None] * self.number
208 self.frames_monochrome_blurred = [None] *self.number
209 self.frames_monochrome_blurred_laplacian = [None] *self.number
210 if self.configuration.frames_normalization:
211 self.frames_average_brightness = [None] *self.number
212 else:
213 self.frames_average_brightness = None
214 self.first_monochrome_index = None
215 self.used_alignment_points = None
216
217 def compute_required_buffer_size(self, buffering_level):
218 """
219 Compute the RAM required to store original images and their derivatives, and other objects
220 which scale with the image size.
221
222 Additional to the original images and their derivatives, the following large objects are
223 allocated during the workflow:
224 calibration.master_dark_frame: pixels * colors (float32)
225 calibration.master_dark_frame_uint8: pixels * colors (uint8)
226 calibration.master_dark_frame_uint16: pixels * colors (uint16)
227 calibration.master_flat_frame: pixels * colors (float32)
228 align_frames.mean_frame: image pixels (int32)
229 align_frames.mean_frame_original: image pixels (int32)
230 alignment_points, reference boxes: < 2 * image pixels (int32)
231 alignment_points, stacking buffers: < 2 * image pixels * colors (float32)
232 stack_frames.stacked_image_buffer: image pixels * colors (float32)
233 stack_frames.number_single_frame_contributions: image pixels (int32)
234 stack_frames.sum_single_frame_weights: image pixels (float32)
235 stack_frames.mask: image pixels (float32)
236 stack_frames.averaged_background: image pixels * colors (float32)
237 stack_frames.stacked_image: image pixels * colors (uint16)
238
239 :param buffering_level: Buffering level parameter.
240 :return: Number of required buffer space in bytes.
241 """
242
243 # Compute the number of image pixels.
244 number_pixel = self.shape[0] * self.shape[1]
245
246 # Compute the size of a monochrome image in bytes.
247 image_size_monochrome_bytes = number_pixel * self.depth / 8
248
249 # Compute the size of an original image in bytes.
250 if self.color:
251 image_size_bytes = 3 * image_size_monochrome_bytes
252 else:
253 image_size_bytes = image_size_monochrome_bytes
254
255 # Compute the size of the monochrome images with Gaussian blur added in bytes.
256 image_size_gaussian_bytes = number_pixel * 2
257
258 # Compute the size of a "Laplacian of Gaussian" in bytes. Remember that it is down-sampled.
259 image_size_laplacian_bytes = number_pixel / \
260 self.configuration.align_frames_sampling_stride ** 2
261
262 # Compute the buffer space per image, based on the buffering level.
263 buffer_original, buffer_monochrome, buffer_gaussian, buffer_laplacian = \
264 Frames.set_buffering(buffering_level)
265 buffer_per_image = 0
266 if buffer_original:
267 buffer_per_image += image_size_bytes
268 if buffer_monochrome:
269 buffer_per_image += image_size_monochrome_bytes
270 if buffer_gaussian:
271 buffer_per_image += image_size_gaussian_bytes
272 if buffer_laplacian:
273 buffer_per_image += image_size_laplacian_bytes
274
275 # Multiply with the total number of frames.
276 buffer_for_all_images = buffer_per_image * self.number
277
278 # Compute the size of additional workspace objects allocated during the workflow.
279 buffer_additional_workspace = number_pixel * 57
280 if self.color:
281 buffer_additional_workspace += number_pixel * 58
282
283 # Return the total buffer space required.
284 return (buffer_for_all_images + buffer_additional_workspace) / 1e9
285
286 def frames(self, index):
287 """
288 Read or look up the original frame object with a given index.
289
290 :param index: Frame index
291 :return: Frame with index "index".
292 """
293
294 if not 0 <= index < self.number:
295 raise ArgumentError("Frame index " + str(index) + " is out of bounds")
296 # print ("Accessing frame " + str(index))
297
298 # If the original frames are to be buffered, read them in one go at the first call to this
299 # method. In this case, a progress bar is displayed in the main GUI.
300 if self.frames_original is None:
301 if self.buffer_original:
302 self.frames_original = []
303 self.signal_step_size = max(int(self.number / 10), 1)
304 for frame_index in range(self.number):
305 # After every "signal_step_size"th frame, send a progress signal to the main GUI.
306 if self.progress_signal is not None and frame_index % self.signal_step_size == 1:
307 self.progress_signal.emit("Read all frames",
308 int(round(10 * frame_index / self.number) * 10))
309 # Read the next frame. If dark/flat correction is active, do the corrections.
310 if self.calibration_matches:
311 self.frames_original.append(self.calibration.correct(
312 self.reader.read_frame(frame_index)))
313 else:
314 self.frames_original.append(self.reader.read_frame(frame_index))
315
316 self.reader.close()
317
318 # If original frames are not buffered, initialize an empty frame list, so frames can be
319 # read later in non-consecutive order.
320 else:
321 self.frames_original = [None] *self.number
322
323 # The original frames are buffered. Just return the frame.
324 if self.buffer_original:
325 return self.frames_original[index]
326
327 # This frame has been cached. Just return it.
328 if self.original_available_index == index:
329 return self.original_available
330
331 # The frame has not been stored for re-use, read it. If dark/flat correction is active, do
332 # the corrections.
333 else:
334 if self.calibration_matches:
335 frame = self.calibration.correct(self.reader.read_frame(index))
336 else:
337 frame = self.reader.read_frame(index)
338
339 # Cache the frame just read.
340 self.original_available = frame
341 self.original_available_index = index
342
343 return frame
344
345 def frames_mono(self, index):
346 """
347 Look up or compute the monochrome version of the frame object with a given index.
348
349 :param index: Frame index
350 :return: Monochrome frame with index "index".
351 """
352
353 if not 0 <= index < self.number:
354 raise ArgumentError("Frame index " + str(index) + " is out of bounds")
355
356 # print("Accessing frame monochrome " + str(index))
357 # The monochrome frames are buffered, and this frame has been stored before. Just return
358 # the frame.
359 if self.frames_monochrome[index] is not None:
360 return self.frames_monochrome[index]
361
362 # If the monochrome frame is cached, just return it.
363 if self.monochrome_available_index == index:
364 return self.monochrome_available
365
366 # The frame has not been stored for re-use, compute it.
367 else:
368
369 # Get the original frame. If it is not cached, this involves I/O.
370 frame_original = self.frames(index)
371
372 # If frames are in color mode produce a B/W version.
373 if self.color:
374 if self.color_index == 3:
375 frame_mono = cvtColor(frame_original, COLOR_RGB2GRAY)
376 else:
377 frame_mono = frame_original[:, :, self.color_index]
378 # Frames are in B/W mode already
379 else:
380 frame_mono = frame_original
381
382 # Normalize the overall frame brightness. The first monochrome frame for which this
383 # method is invoked is taken as the reference. The average brightness of all other
384 # monochrome frames is adjusted to match the brightness of the referenence.
385 if self.configuration.frames_normalization:
386 frame_type = frame_mono.dtype
387 if self.first_monochrome:
388 if frame_type == uint8:
389 self.normalization_lower_threshold = \
390 self.configuration.frames_normalization_threshold
391 self.normalization_upper_threshold = 255
392 else:
393 self.normalization_lower_threshold = \
394 self.configuration.frames_normalization_threshold * 256
395 self.normalization_upper_threshold = 255
396
397 self.frames_average_brightness[index] = cv_mean(
398 threshold(frame_mono, self.normalization_lower_threshold,
399 self.normalization_upper_threshold,
400 THRESH_TOZERO)[1])[0]
401 # self.frames_average_brightness[index] = cv_mean(frame_mono)[0]
402 # Keep the index of the first monochrome frame as the reference index.
403 self.first_monochrome_index = index
404 self.first_monochrome = False
405 # Not the first monochrome frame. Adjust brightness to match the reference.
406 else:
407 self.frames_average_brightness[index] = cv_mean(
408 threshold(frame_mono, self.normalization_lower_threshold,
409 self.normalization_upper_threshold,
410 THRESH_TOZERO)[1])[0]
411 # self.frames_average_brightness[index] = cv_mean(frame_mono)[0]
412 frame_mono = frame_mono * (self.frames_average_brightness[self.first_monochrome_index] /
413 self.frames_average_brightness[index])
414 # Clip the pixel values to the range allowed.
415 if frame_type == uint8:
416 clip(frame_mono, 0, 255, out=frame_mono)
417 else:
418 clip(frame_mono, 0, 65535, out=frame_mono)
419 frame_mono = frame_mono.astype(frame_type)
420
421 # If the monochrome frames are buffered, store it at the current index.
422 if self.buffer_monochrome:
423 self.frames_monochrome[index] = frame_mono
424
425 # If frames are not buffered, cache the current frame.
426 else:
427 self.monochrome_available_index = index
428 self.monochrome_available = frame_mono
429
430 return frame_mono
431
432 def frames_mono_blurred(self, index):
433 """
434 Look up a Gaussian-blurred frame object with a given index.
435
436 :param index: Frame index
437 :return: Gaussian-blurred frame with index "index".
438 """
439
440 if not 0 <= index < self.number:
441 raise ArgumentError("Frame index " + str(index) + " is out of bounds")
442
443 # print("Accessing frame with Gaussian blur " + str(index))
444 # The blurred frames are buffered, and this frame has been stored before. Just return
445 # the frame.
446 if self.frames_monochrome_blurred[index] is not None:
447 return self.frames_monochrome_blurred[index]
448
449 # If the blurred frame is cached, just return it.
450 if self.gaussian_available_index == index:
451 return self.gaussian_available
452
453 # The frame has not been stored for re-use, compute it.
454 else:
455
456 # Get the monochrome frame. If it is not cached, this involves I/O.
457 frame_mono = self.frames_mono(index)
458
459 # If the mono image is 8bit, interpolate it to 16bit.
460 if frame_mono.dtype == uint8:
461 frame_mono = frame_mono.astype(uint16) * 256
462
463 # Compute a version of the frame with Gaussian blur added.
464 frame_monochrome_blurred = GaussianBlur(frame_mono,
465 (self.configuration.frames_gauss_width,
466 self.configuration.frames_gauss_width), 0)
467
468 # If the blurred frames are buffered, store the current frame at the current index.
469 if self.buffer_gaussian:
470 self.frames_monochrome_blurred[index] = frame_monochrome_blurred
471
472 # If frames are not buffered, cache the current frame.
473 else:
474 self.gaussian_available_index = index
475 self.gaussian_available = frame_monochrome_blurred
476
477 return frame_monochrome_blurred
478
479 def frames_mono_blurred_laplacian(self, index):
480 """
481 Look up a Laplacian-of-Gaussian of a frame object with a given index.
482
483 :param index: Frame index
484 :return: LoG of a frame with index "index".
485 """
486
487 if not 0 <= index < self.number:
488 raise ArgumentError("Frame index " + str(index) + " is out of bounds")
489
490 # print("Accessing LoG number " + str(index))
491 # The LoG frames are buffered, and this frame has been stored before. Just return the frame.
492 if self.frames_monochrome_blurred_laplacian[index] is not None:
493 return self.frames_monochrome_blurred_laplacian[index]
494
495 # If the blurred frame is cached, just return it.
496 if self.laplacian_available_index == index:
497 return self.laplacian_available
498
499 # The frame has not been stored for re-use, compute it.
500 else:
501
502 # Get the monochrome frame. If it is not cached, this involves I/O.
503 frame_monochrome_blurred = self.frames_mono_blurred(index)
504
505 # Compute a version of the frame with Gaussian blur added.
506 frame_monochrome_laplacian = convertScaleAbs(Laplacian(
507 frame_monochrome_blurred[::self.configuration.align_frames_sampling_stride,
508 ::self.configuration.align_frames_sampling_stride], CV_32F),
509 alpha=self.alpha)
510
511 # If the blurred frames are buffered, store the current frame at the current index.
512 if self.buffer_laplacian:
513 self.frames_monochrome_blurred_laplacian[index] = frame_monochrome_laplacian
514
515 # If frames are not buffered, cache the current frame.
516 else:
517 self.laplacian_available_index = index
518 self.laplacian_available = frame_monochrome_laplacian
519
520 return frame_monochrome_laplacian
521
522 def reset_alignment_point_lists(self):
523 """
524 Every frame keeps a list with the alignment points for which this frame is among the
525 sharpest ones (so it is used in stacking). Reset this list for all frames.
526
527 :return: -
528 """
529
530 # For every frame initialize the list with used alignment points.
531 self.used_alignment_points = [[] for index in range(self.number)]
532
533 @staticmethod
534 def save_image(filename, image, color=False, avoid_overwriting=True,
535 header="PlanetarySystemStacker"):
536 """
537 Save an image to a file. If "avoid_overwriting" is set to False, images can have either
538 ".png", ".tiff" or ".fits" format.
539
540 :param filename: Name of the file where the image is to be written
541 :param image: ndarray object containing the image data
542 :param color: If True, a three channel RGB image is to be saved. Otherwise, it is assumed
543 that the image is monochrome.
544 :param avoid_overwriting: If True, append a string to the input name if necessary so that
545 it does not match any existing file. If False, overwrite
546 an existing file.
547 :param header: String with information on the PSS version being used (optional).
548 :return: -
549 """
550
551 if avoid_overwriting:
552 # If a file or directory with the given name already exists, append the word "_file".
553 if Path(filename).is_dir():
554 while True:
555 filename += '_file'
556 if not Path(filename).exists():
557 break
558 filename += '.jpg'
559 # If it is a file, try to append "_copy.tiff" to its basename. If it still exists, repeat.
560 elif Path(filename).is_file():
561 suffix = Path(filename).suffix
562 while True:
563 p = Path(filename)
564 filename = Path.joinpath(p.parents[0], p.stem + '_copy' + suffix)
565 if not Path(filename).exists():
566 break
567 else:
568 # If the file name is new and has no suffix, add ".tiff".
569 suffix = Path(filename).suffix
570 if not suffix:
571 filename += '.tiff'
572
573 elif Path(filename).suffix == '.png' or Path(filename).suffix == '.tiff':
574 # Don't care if a file with the given name exists. Overwrite it if necessary.
575 if path.exists(filename):
576 remove(filename)
577 # Write the image to the file. Before writing, convert the internal RGB representation into
578 # the BGR representation assumed by OpenCV.
579 if color:
580 imwrite(str(filename), cvtColor(image, COLOR_RGB2BGR))
581 else:
582 imwrite(str(filename), image)
583
584 elif Path(filename).suffix == '.fits':
585 # Flip image horizontally to preserve orientation
586 image = flip(image, 0)
587 if color:
588 image = moveaxis(image, -1, 0)
589 hdu = fits.PrimaryHDU(image)
590 hdu.header['CREATOR'] = header
591 hdu.writeto(filename, overwrite=True)
592
593 else:
594 raise TypeError("Attempt to write image format other than 'tiff' or 'fits'")
595
596 @staticmethod
597 def read_image(filename):
598 """
599 Read an image (in tiff, fits, png or jpg format) from a file.
600
601 :param filename: Path name of the input image.
602 :return: RGB or monochrome image.
603 """
604
605 name, suffix = splitext(filename)
606
607 # Make sure files with extensions written in large print can be read as well.
608 suffix = suffix.lower()
609
610 # Case FITS format:
611 if suffix in ('.fit', '.fits'):
612 image = fits.getdata(filename)
613
614 # FITS output file from AS3 is 16bit depth file, even though BITPIX
615 # has been set to "-32", which would suggest "numpy.float32"
616 # https://docs.astropy.org/en/stable/io/fits/usage/image.html
617 # To process this data in PSS, do "round()" and convert numpy array to "np.uint16"
618 if image.dtype == '>f4':
619 image = image.round().astype(uint16)
620
621 # If color image, move axis to be able to process the content
622 if len(image.shape) == 3:
623 image = moveaxis(image, 0, -1).copy()
624
625 # Flip image horizontally to recover original orientation
626 image = flip(image, 0)
627
628 # Case other supported image formats:
629 elif suffix in ('.tiff', '.tif', '.png', '.jpg'):
630 input_image = imread(filename, IMREAD_UNCHANGED)
631 if input_image is None:
632 raise IOError("Cannot read image file. Possible cause: Path contains non-ascii characters")
633
634 # If color image, convert to RGB mode.
635 if len(input_image.shape) == 3:
636 image = cvtColor(input_image, COLOR_BGR2RGB)
637 else:
638 image = input_image
639
640 else:
641 raise TypeError("Attempt to read image format other than 'tiff', 'tif',"
642 " '.png', '.jpg' or 'fit', 'fits'")
643
644 return image
645
646
647 if __name__ == "__main__":
648 """
649 This File contains a test main program. It goes through the whole process without using a
650 graphical unser interface. It is not intended to be used in production runs.
651 """
652
653 ####################################### Specify test case ######################################
654
655 input_file = 'E:/SW-Development/Python/PlanetarySystemStacker/Examples/Jupiter/2019-05-26-0115_4-L-Jupiter_ZWO ASI290MM Mini_short.avi'
656
657 ####################################### Specify test case end ##################################
658
659 # Initalize the timer object used to measure execution times of program sections.
660 my_timer = timer()
661
662 print(
663 "\n" +
664 "*************************************************************************************\n"
665 + "Start processing " + str(
666 input_file) +
667 "\n*************************************************************************************")
668 my_timer.create('Execution over all')
669
670 # Get configuration parameters.
671 configuration = Configuration()
672 configuration.initialize_configuration()
673
674 # Read the frames.
675 print("+++ Start reading frames")
676 my_timer.create('Read all frames')
677 try:
678 frames = Frames(configuration, input_file, type='video', buffer_original=True,
679 buffer_monochrome=False, buffer_gaussian=False, buffer_laplacian=False)
680 print("Number of images read: " + str(frames.number))
681 print("Image shape: " + str(frames.shape))
682 except Error as e:
683 print("Error: " + str(e))
684 exit()
685 my_timer.stop('Read all frames')
686
687 # Rank the frames by their overall local contrast.
688 print("+++ Start ranking images")
689 my_timer.create('Ranking images')
690 rank_frames = RankFrames(frames, configuration)
691
692 configuration.frames_normalization = True
693 rank_frames.frame_score()
694 print ("Ranks with normalization: " + str(rank_frames.quality_sorted_indices))
695
696 # Print out timer results.
697 my_timer.stop('Execution over all')
698 my_timer.print()
699
700 # Initalize the timer object used to measure execution times of program sections.
701 my_timer = timer()
702
703 average_brightness_list = frames.frames_average_brightness
704
705 # Now do the same without normalization.
706
707 print(
708 "\n" +
709 "*************************************************************************************\n"
710 + "Start processing " + str(
711 input_file) +
712 "\n*************************************************************************************")
713 my_timer.create('Execution over all')
714
715 # Get configuration parameters.
716 configuration = Configuration()
717 configuration.initialize_configuration()
718
719 # Read the frames.
720 print("+++ Start reading frames")
721 my_timer.create('Read all frames')
722 try:
723 frames = Frames(configuration, input_file, type='video', buffer_original=True,
724 buffer_monochrome=False, buffer_gaussian=False, buffer_laplacian=False)
725 print("Number of images read: " + str(frames.number))
726 print("Image shape: " + str(frames.shape))
727 except Error as e:
728 print("Error: " + str(e))
729 exit()
730 my_timer.stop('Read all frames')
731
732 # Rank the frames by their overall local contrast.
733 print("+++ Start ranking images")
734 my_timer.create('Ranking images')
735 rank_frames = RankFrames(frames, configuration)
736
737 configuration.frames_normalization = False
738 rank_frames.frame_score_no_normalization(average_brightness_list)
739 print("Ranks without normalization: " + str(rank_frames.quality_sorted_indices))
740
741 # Print out timer results.
742 my_timer.stop('Execution over all')
743 my_timer.print()
744