Debian Codegraph @

planetary_system_stacker/Test_programs/rank_frames_extract.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 glob import glob
24 from statistics import mean
25 from time import time
26
27 import matplotlib
28 matplotlib.use('Agg')
29 import matplotlib.pyplot as plt
30 from cv2 import meanStdDev
31 from numpy import array, full
32
33 from configuration import Configuration
34 from exceptions import ArgumentError, NotSupportedError, Error
35 from frames import Frames
36 from miscellaneous import Miscellaneous
37
38
39 class RankFrames(object):
40 """
41 Rank frames according to their overall sharpness. Experiments with different algorithms
42 have been made. The classical "Sobel" algorithm is good but slow. An alternative is
43 implemented in method "local_contrast" in module "miscellaneous".
44
45 """
46
47 def __init__(self, frames, configuration, progress_signal=None):
48 """
49 Initialize the object and instance variables.
50
51 :param frames: Frames object with all video frames
52 :param configuration: Configuration object with parameters
53 :param progress_signal: Either None (no progress signalling), or a signal with the signature
54 (str, int) with the current activity (str) and the progress in
55 percent (int).
56 """
57
58
59 self.shape = frames.shape
60 self.configuration = configuration
61 self.frames = frames
62
63 self.number_original = frames.number
64 self.frame_ranks_original = []
65 self.quality_sorted_indices_original = None
66 self.rank_indices_original = None
67 self.frame_ranks_max_index_original = None
68 self.frame_ranks_max_value_original = None
69
70 self.number = None
71 self.frame_ranks = None
72 self.quality_sorted_indices = None
73 self.rank_indices = None
74 self.frame_ranks_max_index = None
75 self.frame_ranks_max_value = None
76
77 self.progress_signal = progress_signal
78 self.signal_step_size = max(int(self.number_original / 10), 1)
79
80 def frame_score(self):
81 """
82 Compute the frame quality values and normalize them such that the best value is 1.
83
84 :return: -
85 """
86
87 if self.configuration.rank_frames_method == "xy gradient":
88 method = Miscellaneous.local_contrast
89 elif self.configuration.rank_frames_method == "Laplace":
90 method = Miscellaneous.local_contrast_laplace
91 elif self.configuration.rank_frames_method == "Sobel":
92 method = Miscellaneous.local_contrast_sobel
93 else:
94 raise NotSupportedError("Ranking method " + self.configuration.rank_frames_method +
95 " not supported")
96
97 # Reset frames index translation, if active.
98 if self.frames.index_translation_active:
99 self.frames.reset_index_translation()
100
101 # For all frames compute the quality with the selected method.
102 if method != Miscellaneous.local_contrast_laplace:
103 for frame_index in range(self.number_original):
104 frame = self.frames.frames_mono_blurred(frame_index)
105 if self.progress_signal is not None and frame_index % self.signal_step_size == 1:
106 self.progress_signal.emit("Rank all frames",
107 int(round(10*frame_index / self.number_original) * 10))
108 if self.configuration.frames_normalization:
109 self.frame_ranks_original.append(
110 method(frame, self.configuration.rank_frames_pixel_stride) /
111 self.frames.average_brightness(frame_index))
112 else:
113 self.frame_ranks_original.append(
114 method(frame, self.configuration.rank_frames_pixel_stride))
115 else:
116 for frame_index in range(self.number_original):
117 frame = self.frames.frames_mono_blurred_laplacian(frame_index)
118 # self.frame_ranks.append(mean((frame - frame.mean())**2))
119 if self.progress_signal is not None and frame_index % self.signal_step_size == 1:
120 self.progress_signal.emit("Rank all frames",
121 int(round(10*frame_index / self.number_original) * 10))
122 if self.configuration.frames_normalization:
123 self.frame_ranks_original.append(meanStdDev(frame)[1][0][0] /
124 self.frames.average_brightness(frame_index))
125 else:
126 self.frame_ranks_original.append(meanStdDev(frame)[1][0][0])
127
128 # Sort the frame indices in descending order of quality.
129 self.quality_sorted_indices_original = sorted(range(self.number_original),
130 key=self.frame_ranks_original.__getitem__, reverse=True)
131
132 # Compute the inverse index list: For each frame the rank_index is the corresponding index
133 # in the sorted frame_ranks list.
134 self.rank_indices_original = [self.quality_sorted_indices_original.index(index) for index in
135 range(self.number_original)]
136
137 if self.progress_signal is not None:
138 self.progress_signal.emit("Rank all frames", 100)
139
140 # Set the index of the best frame, and normalize all quality values.
141 self.frame_ranks_max_index_original = self.quality_sorted_indices_original[0]
142 self.frame_ranks_max_value_original = self.frame_ranks_original[self.frame_ranks_max_index_original]
143 self.frame_ranks_original /= self.frame_ranks_max_value_original
144
145 # Keep the original ranking data and prepare for index translation. The translation can be
146 # reset later, and the original ranking be re-established.
147 self.number = self.number_original
148 self.frame_ranks = self.frame_ranks_original
149 self.quality_sorted_indices = self.quality_sorted_indices_original
150 self.rank_indices = self.rank_indices_original
151 self.frame_ranks_max_index = self.frame_ranks_max_index_original
152 self.frame_ranks_max_value = self.frame_ranks_max_value_original
153
154 def set_index_translation(self, index_translation):
155 """
156 After frames have been marked to be excluded from the further workflow, update the ranking
157 tables, based on the index translation list from the frames module.
158
159 :param index_translation: List with indices. For each index in the reduced list of frames
160 it gives the corresponding index in the original frame list.
161 :return: -
162 """
163
164 # Set the number of ranks to the number of included frames.
165 self.number = len(index_translation)
166
167 self.frame_ranks = [self.frame_ranks_original[index] for index in index_translation]
168
169 # Sort the frame indices in descending order of quality.
170 self.quality_sorted_indices = sorted(range(self.number),
171 key=self.frame_ranks.__getitem__, reverse=True)
172
173 # Compute the inverse index list: For each frame the rank_index is the corresponding index
174 # in the sorted frame_ranks list.
175 self.rank_indices = [self.quality_sorted_indices.index(index) for index in
176 range(self.number)]
177
178 if self.progress_signal is not None:
179 self.progress_signal.emit("Rank all frames", 100)
180
181 # Set the index of the best frame, and normalize all quality values.
182 self.frame_ranks_max_index = self.quality_sorted_indices[0]
183 self.frame_ranks_max_value = self.frame_ranks[self.frame_ranks_max_index]
184 self.frame_ranks /= self.frame_ranks_max_value
185
186 def reset_index_translation(self):
187 """
188 De-activate index translation and re-establish the original frame ranking data.
189
190 :return: -
191 """
192
193 self.number = self.number_original
194 self.frame_ranks = self.frame_ranks_original
195 self.quality_sorted_indices = self.quality_sorted_indices_original
196 self.rank_indices = self.rank_indices_original
197 self.frame_ranks_max_index = self.frame_ranks_max_index_original
198 self.frame_ranks_max_value = self.frame_ranks_max_value_original
199
200 def find_best_frames(self, number_frames, region_size):
201 """
202 Find the indices of the best "number_frames" frames under the condition that all indices
203 are within an interval of size "region_size".
204
205 :param number_frames: Number of best frames the indices of which are to be found.
206 :param region_size: Maximal width of index interval.
207 :return: (List of frame indices, quality loss, time line position) with:
208 List of frame indices: Indices of frames participating in mean frame computation.
209 quality loss: Loss in average frame quality due to range restriction (%).
210 time line position: Position of the average frame index relative to the total
211 duration of the video.
212 """
213
214 # Check input arguments for validity.
215 if number_frames > region_size:
216 raise ArgumentError("Attempt to find " + str(number_frames) + " good frames in "
217 "an index interval of size " + str(region_size))
218 elif region_size > self.number:
219 raise ArgumentError("Size of best frames region " + str(region_size) + " larger "
220 "than the total number of frames " + str(self.number))
221
222 best_indices = []
223 rank_sum_opt = 0.
224
225 # Construct a sliding window on the full index range. For each window position find the
226 # best "number_frames" frames. Find the window and the best frame set within with the
227 # highest overall score.
228 for start_index in range(self.number - region_size + 1):
229 end_index = start_index + region_size
230 best_indices_in_range = sorted(range(start_index, end_index),
231 key=self.frame_ranks.__getitem__, reverse=True)[
232 :number_frames]
233 rank_sum = sum([self.frame_ranks[i] for i in best_indices_in_range])
234 if rank_sum > rank_sum_opt:
235 rank_sum_opt = rank_sum
236 best_indices = best_indices_in_range
237
238 # Compare the average frame quality with the optimal choice if no time restrictions were
239 # present.
240 rank_sum_global = sum(
241 [self.frame_ranks[i] for i in self.quality_sorted_indices[:number_frames]])
242 quality_loss_percent = round(100. * (rank_sum_global - rank_sum_opt) / rank_sum_global, 1)
243
244 # For the frames included in mean frame computation compute the average position on the
245 # video time line.
246 cog_mean_frame = round(100 * mean(best_indices) / self.number, 1)
247
248 return best_indices, quality_loss_percent, cog_mean_frame
249
250
251 if __name__ == "__main__":
252
253 ROOT = 'D:\SW-Development\Python\PlanetarySystemStacker\Examples\Jupiter_Richard\\'
254
255 names = ROOT+'2020-07-29-2145_3-L-Jupiter_ALTAIRGP224C.ser'
256 type = 'video'
257
258 # Get configuration parameters.
259 configuration = Configuration()
260 configuration.initialize_configuration()
261 try:
262 frames = Frames(configuration, names, type=type)
263 print("Number of images read: " + str(frames.number))
264 print("Image shape: " + str(frames.shape))
265 except Error as e:
266 print("Error: " + e.message)
267 exit()
268
269 # Rank the frames by their overall local contrast.
270 rank_frames = RankFrames(frames, configuration)
271 rank_frames.frame_score()
272
273 for i in range(50):
274 save_frame = frames.frames(rank_frames.quality_sorted_indices[i])
275 writename = ROOT+'%04d.png' % i
276 Frames.save_image(writename, save_frame, color=frames.color, header=configuration.global_parameters_version)
277
278 print(writename)