Debian Codegraph @

planetary_system_stacker/Test_programs/main_program.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 import ctypes
24 import glob
25 import sys
26 import os
27 import platform
28 import traceback
29 from ctypes import CDLL
30
31 import matplotlib
32 matplotlib.use('Agg')
33 import matplotlib.pyplot as plt
34 from skimage import img_as_ubyte
35 from PyQt5 import QtWidgets
36
37 from align_frames import AlignFrames
38 from alignment_points import AlignmentPoints
39 from alignment_point_editor import AlignmentPointEditorWidget
40 from configuration import Configuration
41 from exceptions import NotSupportedError, InternalError, Error
42 from frames import Frames
43 from rank_frames import RankFrames
44 from stack_frames import StackFrames
45 from timer import timer
46
47 def workflow(input_name, input_type='video', roi=None, automatic_ap_creation=True):
48 """
49 Execute the whole stacking workflow for a test case. This can either use a video file (.avi .mov .mp4 .ser)
50 or still images stored in a single directory.
51
52 :param input_name: Video file (.avi .mov .mp4 .ser) or name of a directory containing still images
53 :param input_type: Either "video" or "image" (see "input_name")
54 :param roi: If specified, tuple (y_low, y_high, x_low, x_high) with pixel bounds for "region
55 of interest"
56 :return: average, [average_roi,] color_image_with_aps, stacked_image
57 with: - average: global mean frame
58 - average_roi: mean frame restricted to ROI (only if roi is specified)
59 - color_image_with_aps: mean frame overlaid with alignment points and their
60 boxes (white) and patches (green)
61 """
62
63 # Initalize the timer object used to measure execution times of program sections.
64 my_timer = timer()
65 # Images can either be extracted from a video file or a batch of single photographs. Select
66 # the example for the test run.
67
68 # For video file input, the Frames constructor expects the video file name for "names".
69 if input_type == 'video':
70 names = input_name
71 # For single image input, the Frames constructor expects a list of image file names for "names".
72 else:
73 names = [os.path.join(input_name, name) for name in os.listdir(input_name)]
74 stacked_image_name = input_name + '.stacked.tiff'
75
76 # The name of the alignment point visualization file is derived from the input video name or
77 # the input directory name.
78 ap_image_name = input_name + ".aps.tiff"
79
80 print("\n" +
81 "*************************************************************************************\n"
82 + "Start processing " + str(input_name) +
83 "\n*************************************************************************************")
84 my_timer.create('Execution over all')
85
86 # Get configuration parameters.
87 configuration = Configuration()
88 configuration.initialize_configuration()
89
90 # Read the frames.
91 print("+++ Start reading frames")
92 my_timer.create('Read all frames')
93 try:
94 frames = Frames(configuration, names, type=input_type)
95 print("Number of images read: " + str(frames.number))
96 print("Image shape: " + str(frames.shape))
97 except Error as e:
98 print("Error: " + str(e))
99 exit()
100 my_timer.stop('Read all frames')
101
102 # Rank the frames by their overall local contrast.
103 print("+++ Start ranking images")
104 my_timer.create('Ranking images')
105 rank_frames = RankFrames(frames, configuration)
106 rank_frames.frame_score()
107 my_timer.stop('Ranking images')
108 print("Index of best frame: " + str(rank_frames.frame_ranks_max_index))
109
110 # Initialize the frame alignment object.
111 align_frames = AlignFrames(frames, rank_frames, configuration)
112
113 if configuration.align_frames_mode == "Surface":
114 my_timer.create('Select optimal alignment patch')
115 # Select the local rectangular patch in the image where the L gradient is highest in both x
116 # and y direction. The scale factor specifies how much smaller the patch is compared to the
117 # whole image frame.
118 (y_low_opt, y_high_opt, x_low_opt, x_high_opt) = align_frames.compute_alignment_rect(
119 configuration.align_frames_rectangle_scale_factor)
120 my_timer.stop('Select optimal alignment patch')
121
122 print("optimal alignment rectangle, y_low: " + str(y_low_opt) + ", y_high: " +
123 str(y_high_opt) + ", x_low: " + str(x_low_opt) + ", x_high: " + str(x_high_opt))
124
125 # Align all frames globally relative to the frame with the highest score.
126 print("+++ Start aligning all frames")
127 my_timer.create('Global frame alignment')
128 try:
129 align_frames.align_frames()
130 except NotSupportedError as e:
131 print("Error: " + e.message)
132 exit()
133 except InternalError as e:
134 print("Warning: " + e.message)
135 my_timer.stop('Global frame alignment')
136
137 print("Intersection, y_low: " + str(align_frames.intersection_shape[0][0]) + ", y_high: "
138 + str(align_frames.intersection_shape[0][1]) + ", x_low: " \
139 + str(align_frames.intersection_shape[1][0]) + ", x_high: " \
140 + str(align_frames.intersection_shape[1][1]))
141
142 # Compute the average frame.
143 print("+++ Start computing reference frame")
144 my_timer.create('Compute reference frame')
145 average = align_frames.average_frame()
146 my_timer.stop('Compute reference frame')
147 print("Reference frame computed from the best " + str(
148 align_frames.average_frame_number) + " frames.")
149
150 # If the ROI is to be set to a smaller size than the whole intersection, do so.
151 if roi:
152 print("+++ Start setting ROI and computing new reference frame")
153 my_timer.create('Setting ROI and new reference')
154 average_roi = align_frames.set_roi(roi[0], roi[1], roi[2], roi[3])
155 my_timer.stop('Setting ROI and new reference')
156
157 # Initialize the AlignmentPoints object.
158 my_timer.create('Initialize alignment point object')
159 alignment_points = AlignmentPoints(configuration, frames, rank_frames, align_frames)
160 my_timer.stop('Initialize alignment point object')
161
162 if automatic_ap_creation:
163 # Create alignment points, and create an image with wll alignment point boxes and patches.
164 print("+++ Start creating alignment points")
165 my_timer.create('Create alignment points')
166
167 # If a ROI is selected, alignment points are created in the ROI window only.
168 alignment_points.create_ap_grid()
169
170 my_timer.stop('Create alignment points')
171 print("Number of alignment points selected: " + str(len(alignment_points.alignment_points)) +
172 ", aps dropped because too dim: " + str(alignment_points.alignment_points_dropped_dim) +
173 ", aps dropped because too little structure: " + str(
174 alignment_points.alignment_points_dropped_structure))
175 else:
176 # Open the alignment point editor.
177 app = QtWidgets.QApplication(sys.argv)
178 alignment_point_editor = AlignmentPointEditorWidget(None, configuration, align_frames,
179 alignment_points, None)
180 alignment_point_editor.setMinimumSize(800, 600)
181 alignment_point_editor.showMaximized()
182 app.exec_()
183
184 print("After AP editing, number of APs: " + str(len(alignment_points.alignment_points)))
185 count_updates = 0
186 for ap in alignment_points.alignment_points:
187 if ap['reference_box'] is not None:
188 continue
189 count_updates += 1
190 AlignmentPoints.set_reference_box(ap, alignment_points.mean_frame)
191 print("Buffers allocated for " + str(count_updates) + " alignment points.")
192
193 # Produce an overview image showing all alignment points.
194 if roi:
195 color_image_with_aps = alignment_points.show_alignment_points(average_roi)
196 else:
197 color_image_with_aps = alignment_points.show_alignment_points(average)
198
199 # For each alignment point rank frames by their quality.
200 my_timer.create('Rank frames at alignment points')
201 print("+++ Start ranking frames at alignment points")
202 alignment_points.compute_frame_qualities()
203 my_timer.stop('Rank frames at alignment points')
204
205 # Allocate StackFrames object.
206 stack_frames = StackFrames(configuration, frames, rank_frames, align_frames, alignment_points, my_timer)
207
208 # Stack all frames.
209 print("+++ Start stacking frames")
210 stack_frames.stack_frames()
211
212 # Merge the stacked alignment point buffers into a single image.
213 print("+++ Start merging alignment patches")
214 stacked_image = stack_frames.merge_alignment_point_buffers()
215
216 # If the drizzle factor is 1.5, reduce the pixel resolution of the stacked image buffer
217 # to half the size used in stacking.
218 if configuration.drizzle_factor_is_1_5:
219 print("+++ Start reducing image buffer size")
220 stack_frames.half_stacked_image_buffer_resolution()
221
222 # Save the stacked image as 16bit int (color or mono).
223 my_timer.create('Saving the final image')
224 Frames.save_image(stacked_image_name, stacked_image, color=frames.color,
225 header=configuration.global_parameters_version)
226 my_timer.stop('Saving the final image')
227
228 # Print out timer results.
229 my_timer.stop('Execution over all')
230 my_timer.print()
231
232 # Write the image with alignment points.
233 Frames.save_image(ap_image_name, color_image_with_aps, color=True,
234 header=configuration.global_parameters_version)
235
236 # If a ROI is selected, return both the original and the reduced-size average frame.
237 if roi:
238 return average, average_roi, color_image_with_aps, stacked_image
239 else:
240 return average, color_image_with_aps, stacked_image
241
242
243 if __name__ == "__main__":
244 """
245 This File contains a test main program. It goes through the whole process without using a
246 graphical unser interface. It is not intended to be used in production runs.
247 """
248
249 ####################################### Specify test case ######################################
250 redirect_stdout = False
251 show_results = True
252 input_type = 'video'
253 # input_directory = 'D:/SW-Development/Python/PlanetarySystemStacker/Examples/Moon_2018-03-24'
254 input_directory = 'D:/SW-Development/Python/PlanetarySystemStacker/Examples/Jupiter_short'
255 # input_type = 'image'
256 # input_directory = 'D:/SW-Development/Python/PlanetarySystemStacker/Examples/Moon_2011-04-10'
257 automatic_ap_creation = False
258 roi = None
259 # roi = (400, 700, 300, 800)
260 ####################################### Specify test case end ##################################
261
262 # Redirect standard output to a file if requested.
263 protocol_file = None
264 if redirect_stdout:
265 print("Redirecting stdout, please check Protocol.txt file in input directory.",
266 file=sys.stderr)
267 stdout_saved = sys.stdout
268 protocol_file = open(os.path.join(input_directory, 'Protocol.txt'), 'a')
269 sys.stdout = protocol_file
270
271 # For videos, batch processing is done for all videos in the input directory.
272 if input_type == 'video':
273 input_names = glob.glob(os.path.join(input_directory, '*.avi'))
274 # For images, it is assumed that the input directory contains one or several directories with
275 # image files.
276 else:
277 if input_type != 'image':
278 print("WARNING: Wrong input spec, assuming 'image'")
279 input_directory_content = os.listdir(input_directory)
280 # input_names = [dir for dir in input_directory_content if os.path.isdir(dir)]
281 input_names = []
282 for dir in input_directory_content:
283 dir_abs = os.path.join(input_directory, dir)
284 if os.path.isdir(dir_abs):
285 input_names.append(dir_abs)
286
287 # Feedback on number of files found to process
288 if len(input_names) > 0:
289 print("+++ Start processing", len(input_names), input_type)
290 else:
291 print("+++ No files found to process")
292
293 # Start the processing workflow in batch mode for all AVIs / file directories.
294 try:
295 for input_name in input_names:
296 if roi:
297 average, average_roi, color_image_with_aps, stacked_image = workflow(input_name,
298 input_type=input_type, roi=roi,
299 automatic_ap_creation=automatic_ap_creation)
300 else:
301 average, color_image_with_aps, stacked_image = workflow(input_name,
302 input_type=input_type,
303 automatic_ap_creation=automatic_ap_creation)
304
305 # Interrupt the workflow to display resulting images only if requested.
306 if show_results:
307 # Show the full average frame.
308 plt.imshow(average, cmap='Greys_r')
309 plt.show()
310
311 if roi:
312 # Show the ROI average frame.
313 plt.imshow(average_roi, cmap='Greys_r')
314 plt.show()
315
316 # Show alignment points and patches
317 plt.imshow(color_image_with_aps)
318 plt.show()
319
320 # Convert the stacked image to 8bit and show in Window.
321 plt.imshow(img_as_ubyte(stacked_image))
322 plt.show()
323 except:
324 exec_info = sys.exc_info()
325 if protocol_file is None:
326 traceback.print_tb(exec_info[2])
327 else:
328 traceback.print_tb(exec_info[2], file=protocol_file)
329 print(exec_info[1])
330
331 # Redirect stdout back to normal.
332 if redirect_stdout:
333 sys.stdout = stdout_saved
334 protocol_file.close()