Debian Codegraph @

planetary_system_stacker/frames_old.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 os import path, remove
25 from pathlib import Path
26 from time import time
27
28 import numpy as np
29 from cv2 import imread, VideoCapture, CAP_PROP_FRAME_COUNT, cvtColor, COLOR_BGR2GRAY, \
30 COLOR_BGR2RGB, GaussianBlur, Laplacian, CV_32F, COLOR_RGB2BGR, imwrite, convertScaleAbs
31 from scipy import misc
32
33 from configuration import Configuration
34 from exceptions import TypeError, ShapeError, ArgumentError, WrongOrderingError, Error
35 # from frames import Frames
36
37
38 class FramesOld(object):
39 """
40 This object stores the image data of all frames. Four versions of the original frames are
41 used throughout the data processing workflow. They are (re-)used in the folliwing phases:
42 1. Original (color) frames, type: uint8 / uint16
43 - Frame stacking ("stack_frames.stack_frames")
44 2. Monochrome version of 1., type: uint8
45 - Computing the average frame (only average frame subset, "align_frames.average_frame")
46 3. Gaussian blur added to 2., type: type: uint8
47 - Aligning all frames ("align_frames.align_frames")
48 - Frame stacking ("stack_frames.stack_frames")
49 4. Down-sampled Laplacian of 3., type: uint8
50 - Overall image ranking ("rank_frames.frame_score")
51 - Ranking frames at alignment points("alignment_points.compute_frame_qualities")
52
53 Currently all versions of all frames are stored during the entire workflow. As an
54 alternative, a non-buffered version should be added.
55
56 """
57
58 def __init__(self, configuration, names, type='video', progress_signal=None):
59 """
60 Initialize the Frame object, and read all images. Images can be stored in a video file or
61 as single images in a directory.
62
63 :param configuration: Configuration object with parameters
64 :param names: In case "video": name of the video file. In case "image": list of names for
65 all images.
66 :param type: Either "video" or "image".
67 :param progress_signal: Either None (no progress signalling), or a signal with the signature
68 (str, int) with the current activity (str) and the progress in
69 percent (int).
70 """
71
72 self.configuration = configuration
73 self.progress_signal = progress_signal
74
75 if type == 'image':
76 # Use scipy.misc to read in image files.
77 self.number = len(names)
78 self.signal_step_size = max(int(self.number / 10), 1)
79
80 self.frames_original = []
81 for frame_index, path in enumerate(names):
82 # After every "signal_step_size"th frame, send a progress signal to the main GUI.
83 if self.progress_signal is not None and frame_index%self.signal_step_size == 0:
84 self.progress_signal.emit("Read all frames",
85 int((frame_index / self.number) * 100.))
86 # Read the next frame.
87 frame = imread(path, -1)
88 self.frames_original.append(frame)
89
90 if self.progress_signal is not None:
91 self.progress_signal.emit("Read all frames", 100)
92 self.shape = self.frames_original[0].shape
93 dt0 = self.frames_original[0].dtype
94
95 # Test if all images have the same shape, color type and depth.
96 # If not, raise an exception.
97 for image in self.frames_original:
98 if image.shape != self.shape:
99 raise ShapeError("Images have different size")
100 elif len(self.shape) != len(image.shape):
101 raise ShapeError("Mixing grayscale and color images not supported")
102 if image.dtype != dt0:
103 raise TypeError("Images have different type")
104
105 elif type == 'video':
106 # In case "video", use OpenCV to capture frames from video file. Revert the implicit
107 # conversion from RGB to BGR in OpenCV input.
108 cap = VideoCapture(names)
109 self.number = int(cap.get(CAP_PROP_FRAME_COUNT))
110 self.frames_original = []
111 self.signal_step_size = max(int(self.number / 10), 1)
112 for frame_index in range(self.number):
113 # After every "signal_step_size"th frame, send a progress signal to the main GUI.
114 if self.progress_signal is not None and frame_index%self.signal_step_size == 0:
115 self.progress_signal.emit("Read all frames", int((frame_index/self.number)*100.))
116 # Read the next frame.
117 ret, frame = cap.read()
118 if ret:
119 self.frames_original.append(cvtColor(frame, COLOR_BGR2RGB))
120 else:
121 raise IOError("Error in reading video frame")
122 cap.release()
123 if self.progress_signal is not None:
124 self.progress_signal.emit("Read all frames", 100)
125 self.shape = self.frames_original[0].shape
126 dt0 = self.frames_original[0].dtype
127 else:
128 raise TypeError("Image type " + type + " not supported")
129
130 # Monochrome images are stored as 2D arrays, color images as 3D.
131 if len(self.shape) == 2:
132 self.color = False
133 elif len(self.shape) == 3:
134 self.color = True
135 else:
136 raise ShapeError("Image shape not supported")
137
138 # Set the depth value of all images to either 16 or 8 bits.
139 if dt0 == 'uint16':
140 self.depth = 16
141 elif dt0 == 'uint8':
142 self.depth = 8
143 else:
144 raise TypeError("Frame type " + str(dt0) + " not supported")
145
146 # Initialize lists of monochrome frames (with and without Gaussian blur) and their
147 # Laplacians.
148 self.frames_monochrome = None
149 self.frames_monochrome_blurred = None
150 self.frames_monochrome_blurred_laplacian = None
151 self.used_alignment_points = None
152
153 def frames(self, index):
154 """
155 Look up the original frame object with a given index.
156
157 :param index: Frame index
158 :return: Frame with index "index".
159 """
160
161 # # Code for positioning at arbitrary index.
162 # # Check for valid frame number.
163 # if 0 <= index < self.number:
164 # # Set frame position
165 # cap.set(cv2.CAP_PROP_POS_FRAMES, index)
166
167 if not 0<=index<self.number:
168 raise ArgumentError("Frame index " + str(index) + " is out of bounds")
169 # print ("Accessing frame " + str(index))
170 return self.frames_original[index]
171
172 def frames_mono(self, index):
173 """
174 Look up the monochrome version of the frame object with a given index.
175
176 :param index: Frame index
177 :return: Monochrome frame with index "index".
178 """
179
180 if not 0 <= index < self.number:
181 raise ArgumentError("Frame index " + str(index) + " is out of bounds")
182 if self.frames_monochrome is not None:
183 # print("Accessing frame monochrome " + str(index))
184 return self.frames_monochrome[index]
185 else:
186 raise WrongOrderingError("Attempt to look up a monochrome frame before computing it")
187
188 def frames_mono_blurred(self, index):
189 """
190 Look up a Gaussian-blurred frame object with a given index.
191
192 :param index: Frame index
193 :return: Gaussian-blurred frame with index "index".
194 """
195
196 if not 0 <= index < self.number:
197 raise ArgumentError("Frame index " + str(index) + " is out of bounds")
198 if self.frames_monochrome_blurred is not None:
199 # print("Accessing frame with Gaussian blur " + str(index))
200 return self.frames_monochrome_blurred[index]
201 else:
202 raise WrongOrderingError("Attempt to look up a Gaussian-blurred frame version before"
203 " computing it")
204
205 def frames_mono_blurred_laplacian(self, index):
206 """
207 Look up a Laplacian-of-Gaussian of a frame object with a given index.
208
209 :param index: Frame index
210 :return: LoG of a frame with index "index".
211 """
212
213 if not 0 <= index < self.number:
214 raise ArgumentError("Frame index " + str(index) + " is out of bounds")
215 if self.frames_monochrome_blurred_laplacian is not None:
216 # print("Accessing LoG number " + str(index))
217 return self.frames_monochrome_blurred_laplacian[index]
218 else:
219 raise WrongOrderingError("Attempt to look up a LoG frame version before computing it")
220
221 def reset_alignment_point_lists(self):
222 """
223 Every frame keeps a list with the alignment points for which this frame is among the
224 sharpest ones (so it is used in stacking). Reset this list for all frames.
225
226 :return: -
227 """
228
229 # For every frame initialize the list with used alignment points.
230 self.used_alignment_points = [[] for frame_index in range(self.number)]
231
232 def add_monochrome(self, color):
233 """
234 Create monochrome versions of all frames. Add a list of monochrome frames
235 "self.frames_mono". If the original frames are monochrome, just point the monochrome frame
236 list to the original images (no deep copy!). Also, add a blurred version of the frame list
237 (using a Gaussian filter) "self.frames_mono_blurred", and the Laplacian of that image.
238
239 :param color: Either "red" or "green", "blue", or "panchromatic"
240 :return: -
241 """
242
243 if self.color:
244 colors = ['red', 'green', 'blue', 'panchromatic']
245 if not color in colors:
246 raise ArgumentError("Invalid color selected for channel extraction")
247 self.frames_monochrome = []
248 elif self.depth == 8:
249 self.frames_monochrome = self.frames_original
250
251 self.frames_monochrome_blurred = []
252 self.frames_monochrome_blurred_laplacian = []
253
254 for frame_index, frame in enumerate(self.frames_original):
255 # After every "signal_step_size"th frame, send a progress signal to the main GUI.
256 if self.progress_signal is not None and frame_index % self.signal_step_size == 0:
257 self.progress_signal.emit("Gaussians / Laplacians",
258 int((frame_index / self.number) * 100.))
259
260 # If frames are in color mode, or the depth is 16bit, produce a 8bit B/W version.
261 if self.color or self.depth != 8:
262 # If frames are in color mode, create a monochrome version with same depth.
263 if self.color:
264 if color == 'panchromatic':
265 frame_mono = cvtColor(frame, COLOR_BGR2GRAY)
266 else:
267 frame_mono = frame[:, :, colors.index(color)]
268 else:
269 frame_mono = frame
270
271 # If depth is larger than 8bit, reduce the depth to 8bit.
272 if self.depth != 8:
273 frame_mono = ((frame_mono) / 255.).astype(np.uint8)
274
275 self.frames_monochrome.append(frame_mono)
276
277 # Add a version of the frame with Gaussian blur added.
278 frame_monochrome_blurred = GaussianBlur(self.frames_monochrome[frame_index], (
279 self.configuration.frames_gauss_width, self.configuration.frames_gauss_width), 0)
280 self.frames_monochrome_blurred.append(frame_monochrome_blurred)
281
282 # Compute the scaling factor for "convertScaleAbs" depending on the data type of the
283 # monochrome image. The Laplacian is 8bit. If the monochrome image is 16bit, values
284 # have to be scaled down.
285
286 # Add the Laplacian of the down-sampled blurred image.
287 if self.configuration.rank_frames_method == "Laplace":
288 self.frames_monochrome_blurred_laplacian.append(convertScaleAbs(Laplacian(
289 frame_monochrome_blurred[::self.configuration.align_frames_sampling_stride,
290 ::self.configuration.align_frames_sampling_stride], CV_32F),
291 alpha=1))
292
293 if self.progress_signal is not None:
294 self.progress_signal.emit("Gaussians / Laplacians", 100)
295
296 def save_image(self, filename, image, color=False, avoid_overwriting=True):
297 """
298 Save an image to a file.
299
300 :param filename: Name of the file where the image is to be written
301 :param image: ndarray object containing the image data
302 :param color: If True, a three channel RGB image is to be saved. Otherwise, monochrome.
303 :param avoid_overwriting: If True, append a string to the input name if necessary so that
304 it does not match any existing file. If False, overwrite
305 an existing file.
306 :return: -
307 """
308
309 if avoid_overwriting:
310 # If a file or directory with the given name already exists, append the word "_file".
311 if Path(filename).is_dir():
312 while True:
313 filename += '_file'
314 if not Path(filename).exists():
315 break
316 filename += '.jpg'
317 # If it is a file, try to append "_copy.tiff" to its basename. If it still exists, repeat.
318 elif Path(filename).is_file():
319 suffix = Path(filename).suffix
320 while True:
321 p = Path(filename)
322 filename = Path.joinpath(p.parents[0], p.stem + '_copy' + suffix)
323 if not Path(filename).exists():
324 break
325 else:
326 # If the file name is new and has no suffix, add ".tiff".
327 suffix = Path(filename).suffix
328 if not suffix:
329 filename += '.tiff'
330
331 # Don't care if a file with the given name exists. Overwrite it if necessary.
332 elif path.exists(filename):
333 remove(filename)
334
335 # Write the image to the file. Before writing, convert the internal RGB representation into
336 # the BGR representation assumed by OpenCV.
337 if color:
338 imwrite(str(filename), cvtColor(image, COLOR_RGB2BGR))
339 else:
340 imwrite(str(filename), image)
341
342
343 if __name__ == "__main__":
344
345 # Images can either be extracted from a video file or a batch of single photographs. Select
346 # the example for the test run.
347 type = 'image'
348 if type == 'image':
349 # names = glob('Images/2012_*.tif')
350 # names = glob('D:\SW-Development\Python\PlanetarySystemStacker\Examples\Moon_2011-04-10\South\*.TIF')
•351 names = glob(r'D:\SW-Development\Python\PlanetarySystemStacker\Examples\Moon_2019-01-20\Images\*.TIF')
352 else:
353 names = 'Videos/short_video.avi'
354
355 # Get configuration parameters.
356 configuration = Configuration()
357 configuration.initialize_configuration()
358
359 start = time()
360 try:
361 frames_old = FramesOld(configuration, names, type=type)
362 print("Frames old: Number of images read: " + str(frames_old.number))
363 print("Image shape: " + str(frames_old.shape))
364 except Error as e:
365 print("Error: " + e.message)
366 exit()
367 end = time()
368 print("Read " + str(frames_old.number) + " frames in " + str(end-start) + " seconds.")
369
370 # Create monochrome versions of all frames. If the original frames are monochrome, just point
371 # the monochrome frame list to the original images (no deep copy!).
372 try:
373 frames_old.add_monochrome(configuration.frames_mono_channel)
374 except ArgumentError as e:
375 print("Error: " + e.message)
376 exit()
377
378 # try:
379 # frames = Frames(configuration, names, type=type,
380 # buffer_original=False, buffer_monochrome=False, buffer_gaussian=False,
381 # buffer_laplacian=False)
382 # print("\nFrames: Number of images: " + str(frames.number))
383 # print("Image shape: " + str(frames.shape))
384 # except Error as e:
385 # print("Error: " + e.message)
386 # exit()
387 #
388 # indices = [1, 0, 2, 2, 8]
389 #
390 # for index in indices:
391 # frame_old = frames_old.frames_mono_blurred_laplacian(index)
392 # frame = frames.frames_mono_blurred_laplacian(index)
393 # difference = np.max(np.abs(frame - frame_old))
394 # print ("Error for frame " + str(index) + ": " + str(difference))