| 1 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 96 |
|
| 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 |
|
| 107 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 147 |
|
| 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 |
|
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
if not 0<=index<self.number: |
| 168 |
raise ArgumentError("Frame index " + str(index) + " is out of bounds") |
| 169 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 261 |
if self.color or self.depth != 8: |
| 262 |
|
| 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 |
|
| 272 |
if self.depth != 8: |
| 273 |
frame_mono = ((frame_mono) / 255.).astype(np.uint8) |
| 274 |
|
| 275 |
self.frames_monochrome.append(frame_mono) |
| 276 |
|
| 277 |
|
| 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 |
|
| 283 |
|
| 284 |
|
| 285 |
|
| 286 |
|
| 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 |
|
| 311 |
if Path(filename).is_dir(): |
| 312 |
while True: |
| 313 |
filename += '_file' |
| 314 |
if not Path(filename).exists(): |
| 315 |
break |
| 316 |
filename += '.jpg' |
| 317 |
|
| 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 |
|
| 327 |
suffix = Path(filename).suffix |
| 328 |
if not suffix: |
| 329 |
filename += '.tiff' |
| 330 |
|
| 331 |
|
| 332 |
elif path.exists(filename): |
| 333 |
remove(filename) |
| 334 |
|
| 335 |
|
| 336 |
|
| 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 |
|
| 346 |
|
| 347 |
type = 'image' |
| 348 |
if type == 'image': |
| 349 |
|
| 350 |
|
| •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 |
|
| 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 |
|
| 371 |
|
| 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 |
|
| 379 |
|
| 380 |
|
| 381 |
|
| 382 |
|
| 383 |
|
| 384 |
|
| 385 |
|
| 386 |
|
| 387 |
|
| 388 |
|
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
|
| 393 |
|
| 394 |
|