-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathCMN_binViewer.py
executable file
·4150 lines (3159 loc) · 163 KB
/
CMN_binViewer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright notice (Revised BSD License)
# Copyright (c) 2016, Denis Vida
# Copyright (c) 2012, Almar Klein, Ant1, Marius van Voorden (images2gif.py)
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification, are permitted provided
# that the following conditions are met:
# • Redistributions of source code must retain the above copyright notice, this list of conditions and the
# following disclaimer.
# • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
# the following disclaimer in the documentation and/or other materials provided with the distribution.
# • Neither the name of the Croatian Meteor Network nor the names of its contributors may be used to
# endorse or promote products derived from this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANT ABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DENIS VIDA BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.
import os
import sys
import errno
import argparse
import gc
import glob
import time
import datetime
import subprocess
import platform
# python 2/3 compatability
if sys.version_info[0] < 3:
import Tkinter as tk
import tkFileDialog
import tkMessageBox
from Tkinter import IntVar, BooleanVar, StringVar, DoubleVar, Frame, ACTIVE, END, Listbox, Menu, \
PhotoImage, NORMAL, DISABLED, Entry, Scale, Button
from ttk import Label, Style, LabelFrame, Checkbutton, Radiobutton, Scrollbar
else:
import tkinter as tk
import tkinter.filedialog as tkFileDialog
import tkinter.messagebox as tkMessageBox
from tkinter import IntVar, BooleanVar, StringVar, DoubleVar, Frame, ACTIVE, END, Listbox, Menu, \
PhotoImage, NORMAL, DISABLED, Entry, Scale, Button
from tkinter.ttk import Label, Style, LabelFrame, Checkbutton, Radiobutton, Scrollbar
import threading
import logging
import logging.handlers
import traceback
from shutil import copy2
import numpy as np
from PIL import Image as img
from PIL import ImageTk
from PIL import ImageChops
from FF_bin_suite import readFF, buildFF, colorize_maxframe, max_nomean, load_dark, load_flat, process_array, \
saveImage, make_flat_frame, makeGIF, get_detection_only, get_processed_frames, adjust_levels, \
get_FTPdetect_coordinates, markDetections, deinterlace_array_odd, deinterlace_array_even, rescaleIntensity
from module_confirmationClass import Confirmation
# import module_exportLogsort as exportLogsort
from module_highlightMeteorPath import highlightMeteorPath
from module_CAMS2CMN import convert_rmsftp_to_cams
from makeMP4 import makeMP4
version = "3.37.1"
# set to true to disable the video radiobutton
disable_UI_video = False
global_bg = "Black"
global_fg = "Gray"
config_file = 'config.ini'
run_dir = os.path.abspath(".")
log_directory = 'CMN_binViewer_logs'
tempImage = 0
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
class BackgroundTask():
def __init__(self, taskFuncPointer):
self.__taskFuncPointer_ = taskFuncPointer
self.__workerThread_ = None
self.__isRunning_ = False
def taskFuncPointer(self):
return self.__taskFuncPointer_
def isRunning(self):
return self.__isRunning_ and self.__workerThread_.is_alive()
def start(self):
if not self.__isRunning_:
self.__isRunning_ = True
self.__workerThread_ = self.WorkerThread(self)
self.__workerThread_.start()
def stop(self):
self.__isRunning_ = False
class WorkerThread(threading.Thread):
def __init__(self, bgTask):
threading.Thread.__init__(self)
self.__bgTask_ = bgTask
def run(self):
try:
self.__bgTask_.taskFuncPointer()(self.__bgTask_.isRunning)
except Exception as e:
print(repr(e))
self.__bgTask_.stop()
def getSysTime():
if sys.version_info[0] < 3:
return time.clock()
else:
return time.process_time()
def mkdir_p(path):
""" Makes a directory and handles all errors.
"""
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST:
pass
else:
raise
class StyledButton(Button):
""" Button with style.
"""
def __init__(self, *args, **kwargs):
Button.__init__(self, *args, **kwargs)
self.configure(foreground = global_fg, background = global_bg, borderwidth = 3)
class StyledEntry(Entry):
""" Entry box with style.
"""
def __init__(self, *args, **kwargs):
Entry.__init__(self, *args, **kwargs)
self.configure(foreground = global_fg, background = global_bg, insertbackground = global_fg, disabledbackground = global_bg, disabledforeground = "DimGray")
class ConstrainedEntry(StyledEntry):
""" Entry box with constrained values which can be input (e.g. 0-255).
"""
def __init__(self, *args, **kwargs):
StyledEntry.__init__(self, *args, **kwargs)
self.maxvalue = 255
vcmd = (self.register(self.on_validate), "%P")
self.configure(validate="key", validatecommand=vcmd)
# self.configure(foreground = global_fg, background = global_bg, insertbackground = global_fg)
def disallow(self):
""" Pings a bell on values which are out of bound.
"""
self.bell()
def update_value(self, maxvalue):
""" Updates values in the entry box.
"""
self.maxvalue = maxvalue
vcmd = (self.register(self.on_validate), "%P")
self.configure(validate="key", validatecommand=vcmd)
def on_validate(self, new_value):
""" Checks if entered value is within bounds.
"""
try:
if new_value.strip() == "":
return True
value = int(new_value)
if value < 0 or value > self.maxvalue:
self.disallow()
return False
except ValueError:
self.disallow()
return False
return True
class ExternalVideo(Frame):
""" Class for handling external video showing in another window.
"""
def __init__(self, parent):
Frame.__init__(self, parent, bg = global_bg)
parent.configure(bg = global_bg) # Set backgound color
parent.grid_columnconfigure(0, weight=1)
parent.grid_rowconfigure(0, weight=1)
self.grid(sticky="NSEW") # Expand frame to all directions
self.parent = parent
self.parent.title("External video")
# Video label
blankImage = None
self.externalVideoLabel = Label(self, image = blankImage)
self.externalVideoLabel.image = blankImage
self.externalVideoLabel.grid(row = 1, column = 1)
def update(self, img_path, current_image, start_frame, end_frame, fps, data_type, dimensions=1, min_lvl=0,
gamma=1, max_lvl=255, external_guidelines=0, HT_rho=0, HT_phi=0):
""" Updates external video parameters on image change and runs the video.
"""
self.img_path = img_path
self.fps = fps
self.dimensions = dimensions
self.external_video_FFbinRead = readFF(img_path, datatype=data_type)
# Apply levels and gamma
self.external_video_FFbinRead.maxpixel = adjust_levels(self.external_video_FFbinRead.maxpixel,
min_lvl, gamma, max_lvl)
self.external_video_FFbinRead.avepixel = adjust_levels(self.external_video_FFbinRead.avepixel,
min_lvl, gamma, max_lvl)
if external_guidelines:
# Draw meteor guidelines
self.external_video_FFbinRead.avepixel = highlightMeteorPath(self.external_video_FFbinRead.avepixel,
HT_rho, HT_phi)
self.external_video_ncols = self.external_video_FFbinRead.ncols - 1
self.external_video_nrows = self.external_video_FFbinRead.nrows - 1
if dimensions == 2:
# 1.5 size external video
self.external_video_ncols = int(self.external_video_ncols / 1.22474487139)
self.external_video_nrows = int(self.external_video_nrows / 1.22474487139)
elif dimensions == 3:
# Half size external video
self.external_video_ncols = int(self.external_video_ncols / 1.41421356237)
self.external_video_nrows = int(self.external_video_nrows / 1.41421356237)
elif dimensions == 4:
# Quarter size external video
self.external_video_ncols = int(self.external_video_ncols / 2)
self.external_video_nrows = int(self.external_video_nrows / 2)
# Set window size
self.parent.geometry(str(self.external_video_ncols) + "x" + str(self.external_video_nrows))
# Add a few frames to each side, to better see the detection
start_temp = start_frame - 5
end_temp = end_frame + 5
start_frame = 0 if start_temp < 0 else start_temp
if data_type == 1:
# CAMS data type
end_frame = 255 if end_temp > 255 else end_temp
elif data_type == 2:
# Skypatrol data dype
end_frame = 1500 if end_temp > 1500 else end_temp
elif data_type == 3:
# FITS file type
end_frame = self.external_video_FFbinRead.nframes if end_temp > self.external_video_FFbinRead.nframes else end_temp
self.external_video_startFrame = start_frame
self.external_video_endFrame = end_frame
self.external_video_counter = start_frame
# Cache everything under 75 frames
if (self.external_video_endFrame - self.external_video_startFrame + 1) <= 75:
self.cache_flag = True
else:
self.cache_flag = False
# Delete cache
self.external_videoCache = None
# Collect garbage and free memory
gc.collect()
self.external_videoCache = []
self.external_video_FirstRun = True
# Run external video
self.run()
def run(self):
""" Run external video.
"""
global stop_external_video
start_time = getSysTime() # Time the script below to achieve correct FPS
if self.external_video_FirstRun:
if self.cache_flag is True:
# Cache video files during first run
img_array = buildFF(self.external_video_FFbinRead, self.external_video_counter, videoFlag = True)
self.external_videoCache.append(img_array)
else:
img_array = buildFF(self.external_video_FFbinRead, self.external_video_counter, videoFlag = True)
else:
if self.cache_flag is True:
img_array = self.external_videoCache[self.external_video_counter - self.external_video_startFrame] # Read cached video frames in consecutive runs
else:
img_array = buildFF(self.external_video_FFbinRead, self.external_video_counter, videoFlag = True)
temp_image = ImageTk.PhotoImage(img.fromarray(img_array).resize((self.external_video_ncols, self.external_video_nrows), img.BILINEAR)) #Prepare for showing
self.externalVideoLabel.configure(image = temp_image) #Set image to image label
self.externalVideoLabel.image = temp_image
# Deal with frame counter
if self.external_video_counter == self.external_video_endFrame:
self.external_video_counter = self.external_video_startFrame
self.external_video_FirstRun = False
else:
self.external_video_counter += 1
# Sleep for 1/FPS with corrected time for script running time
end_time = getSysTime()
script_time = float(end_time - start_time)
if not script_time > 1.0 / self.fps:
delay = 1.0 / self.fps - script_time
else:
delay = 0.001
if not stop_external_video:
self.after(int(delay * 1000), self.run)
class ConfirmationVideo(Frame):
""" Class for handling Confirmation video showing in another window.
"""
def __init__(self, parent):
Frame.__init__(self, parent, bg = global_bg)
parent.geometry("256x256")
parent.configure(bg = global_bg) # Set backgound color
parent.grid_columnconfigure(0, weight=1)
parent.grid_rowconfigure(0, weight=1)
self.grid(sticky="NSEW") # Expand frame to all directions
self.parent = parent
self.parent.title("Detection centered video")
# Video label
blankImage = None
self.confirmationVideoLabel = Label(self, image = blankImage)
self.confirmationVideoLabel.image = blankImage
self.confirmationVideoLabel.grid(row = 1, column = 1)
def update(self, img_path, current_image, meteorNo, FTPdetectinfoContents, fps, data_type, cropSize = 64):
""" Updates confirmation video parameters on image change and runs the video.
"""
self.img_path = img_path
self.cropSize = cropSize
self.fps = fps
self.confirmation_video_segmentList = get_FTPdetect_coordinates(FTPdetectinfoContents, current_image, meteorNo)
self.confirmation_video_FFbinRead = readFF(img_path, datatype = data_type)
self.confirmation_video_ncols = self.confirmation_video_FFbinRead.ncols - 1
self.confirmation_video_nrows = self.confirmation_video_FFbinRead.nrows - 1
self.confirmation_video_startFrame = 0
self.confirmation_video_endFrame = len(self.confirmation_video_segmentList[0]) - 1
self.confirmation_video_counter = 0
# Delete cache
self.confirmation_videoCache = None
# Collect garbage and free memory
gc.collect()
self.confirmation_videoCache = []
self.confirmation_video_FirstRun = True
# Run confirmation video
self.run()
def run(self):
""" Run the confirmation video.
"""
global stop_confirmation_video
cropSize = self.cropSize
start_time = getSysTime()
if self.confirmation_video_FirstRun:
coordinate = self.confirmation_video_segmentList[0][self.confirmation_video_counter]
frame, x, y = coordinate
x = int(round(x, 0))
# Make sure each center row is even
y = int(y)
if y % 2 == 1:
y += 1
x_left = x - cropSize
y_left = y - cropSize
x_right = x + cropSize
y_right = y + cropSize
x_diff = 0
y_diff = 0
x_end = cropSize * 2
y_end = cropSize * 2
fillZeoresFlag = False
if x_left < 0:
fillZeoresFlag = True
x_diff = -x_left
x_end = cropSize * 2
x_left = 0
if y_left < 0:
fillZeoresFlag = True
y_diff = -y_left
y_end = cropSize * 2
y_left = 0
if x_right > self.confirmation_video_ncols:
fillZeoresFlag = True
x_diff = 0
x_end = cropSize * 2 - (x_right - self.confirmation_video_ncols)
x_right = self.confirmation_video_ncols
if y_right > self.confirmation_video_nrows:
fillZeoresFlag = True
y_diff = 0
y_end = cropSize * 2 - (y_right - self.confirmation_video_nrows - 1)
y_right = self.confirmation_video_nrows + 1
imageArray = buildFF(self.confirmation_video_FFbinRead, int(frame), videoFlag = True)
# If croped area is in the corner, fill corner with zeroes
if fillZeoresFlag:
cropedArray = np.zeros(shape =(cropSize * 2, cropSize * 2))
tempCrop = imageArray[y_left:y_right, x_left:x_right]
cropedArray[y_diff:y_end, x_diff:x_end] = tempCrop
else:
cropedArray = imageArray[y_left:y_right, x_left:x_right]
if frame % 1 == 0:
# Deinterlace odd
cropedArray = deinterlace_array_odd(cropedArray)
else:
# Deinterlace even
cropedArray = deinterlace_array_even(cropedArray)
self.confirmation_videoCache.append(np.copy(cropedArray))
else:
cropedArray = self.confirmation_videoCache[self.confirmation_video_counter]
tempImage = ImageTk.PhotoImage(img.fromarray(cropedArray).resize((256, 256), img.BICUBIC)) # Prepare for showing
self.confirmationVideoLabel.configure(image = tempImage) # Set image to image label
self.confirmationVideoLabel.image = tempImage
# Deal with frame counter
if self.confirmation_video_counter == self.confirmation_video_endFrame:
self.confirmation_video_counter = 0
self.confirmation_video_FirstRun = False
else:
self.confirmation_video_counter += 1
# Sleep for 1/FPS with corrected time for script running time
end_time = getSysTime()
script_time = float(end_time - start_time)
slowFactor = 1.1
if not script_time > slowFactor * 1.0 / self.fps:
delay = slowFactor * 1.0 / self.fps - script_time
else:
delay = 0.001
if not stop_confirmation_video:
self.after(int(delay * 1000), self.run)
class SuperBind():
""" Enable any key to have unique events on being pressed once or being held down longer.
pressed_function is called when the key is being held down.
release_function is called when the key is pressed only once or released after pressing it constantly
Arguments:
key - key to be pressed, e.g. 'a'
master - 'self' from master class
root - Tkinter root of master class
pressed_function - function to be called when the key is pressed constantly
release_function - function to be called when the key is released or pressed only once
repeat_press - if True, pressed_function will be called before release_function on only one key press (default True)
no_repeat_function - will be run if repeat_press is False (default is None)
e.g. calling from master class:
a_key = SuperBind('a', self, self.root, self.print_press, self.print_release)
"""
def __init__(self, key, master, root, pressed_function, release_function, repeat_press = True, no_repeat_function = None):
self.afterId = None
self.master = master
self.root = root
self.repeat_press = repeat_press
self.no_repeat_function = no_repeat_function
self.pressed_function = pressed_function
self.release_function = release_function
self.root.bind('<KeyPress-' + key + '>', self.keyPress)
self.root.bind('<KeyRelease-' + key + '>', self.keyRelease)
self.pressed_counter = 0
def keyPress(self, event):
if self.afterId is not None:
self.master.after_cancel(self.afterId)
self.afterId = None
self.pressed_function()
else:
if self.pressed_counter > 1:
self.pressed_function()
else:
if self.repeat_press:
# When this is true, pressed function will be called and release function will be called both
self.release_function()
else:
if self.no_repeat_function is not None:
# If a special function is provided, run it instead
self.no_repeat_function()
self.pressed_counter += 1
def keyRelease(self, event):
self.afterId = self.master.after_idle(self.processRelease, event)
def processRelease(self, event):
self.release_function()
self.afterId = None
self.pressed_counter = 0
class SuperUnbind():
""" Unbind all that was bound by SuperBind.
"""
def __init__(self, key, master, root):
self.master = master
self.root = root
self.root.unbind('<KeyPress-' + key + '>')
self.root.unbind('<KeyRelease-' + key + '>')
class BinViewer(Frame):
""" Main CMN_binViewer window.
"""
def __init__(self, parent, dir_path=None, confirmation=False, ftpdetectfile=''):
""" Runs only when the viewer class is created (i.e. on the program startup only).
Arguments:
parent: [tk object] Tk root handle.
Keyword arguments:
dir_path: [str] If given, binviewer will open the given directory. None by default.
confirmation: [bool] If True, BinViewer will start in confirmation mode. False by default.
"""
# parent.geometry("1366x768")
if dir_path is not None:
if dir_path[-1] == os.sep:
dir_path = dir_path[:-1]
Frame.__init__(self, parent, bg = global_bg)
parent.configure(bg = global_bg) # Set backgound color
parent.grid_columnconfigure(0, weight=1)
parent.grid_rowconfigure(0, weight=1)
self.grid(sticky="NSEW") # Expand frame to all directions
# self.grid_propagate(0)
self.parent = parent
# DEFINE INITIAL VARIABLES
self.filter_no = 6 # Number of filters
self.dir_path = os.path.abspath(os.sep)
self.station_id = ''
self.layout_vertical = BooleanVar() # Layout variable
self.ffmpeg_path_win = ''
# Read configuration file
orientation, fps_config, self.dir_path, external_video_config, edge_marker, external_guidelines, image_resize_factor, userejected, ffmpeg_path_win = self.readConfig()
# in case a relative path was stored
self.dir_path = os.path.expanduser(self.dir_path)
# Image resize factor
self.image_resize_factor = IntVar()
self.image_resize_factor.set(image_resize_factor)
self.prev_resize_factor = IntVar()
self.prev_resize_factor.set(image_resize_factor)
if orientation == 0:
self.layout_vertical.set(False)
else:
self.layout_vertical.set(True)
self.mode = IntVar()
self.minimum_frames = IntVar()
self.minimum_frames.set(0)
self.detection_dict = {}
self.data_type_var = IntVar() # For GUI
self.data_type_var.set(0) # Set to Auto
self.data_type = IntVar() # For backend
self.data_type.set(1) # Set to CAMS
self.filter = IntVar()
self.old_filter = IntVar()
self.block_img_update = False
self.img_data = 0
self.current_image = ''
self.current_image_cols = 768
self.old_image = ''
self.old_confirmation_image = ''
self.img_name_type = 'maxpixel'
self.dark_status = BooleanVar()
self.dark_status.set(False)
self.flat_status = BooleanVar()
self.flat_status.set(False)
self.dark_name = StringVar()
self.dark_name.set("dark.bmp")
self.flat_name = StringVar()
self.flat_name.set("flat.bmp")
self.deinterlace = BooleanVar()
self.deinterlace.set(False)
self.invert = BooleanVar()
self.invert.set(False)
self.hold_levels = BooleanVar()
self.hold_levels.set(False)
self.arcsinh_status = BooleanVar()
self.arcsinh_status.set(False)
self.sort_folder_path = StringVar()
self.sort_folder_path.set("chosen")
self.bin_list = StringVar()
self.print_name_status = BooleanVar()
self.print_name_status.set(False)
self.start_frame = IntVar()
self.start_frame.set(0)
self.end_frame = IntVar()
self.end_frame.set(255)
self.temp_frame = IntVar()
self.temp_frame.set(self.start_frame.get())
self.stop_confirmation_video = BooleanVar()
self.stop_confirmation_video.set(True)
self.externalVideoOn = IntVar()
self.externalVideoOn.set(external_video_config)
self.bgtask = BackgroundTask(self.showVideoMainWindow)
self.HT_rho = 0
self.HT_phi = 0
self.edge_marker = IntVar()
self.edge_marker.set(edge_marker)
self.userejected = IntVar()
self.userejected.set(userejected)
self.external_guidelines = IntVar()
self.external_guidelines.set(external_guidelines)
self.ffmpeg_path_win = ffmpeg_path_win
# GIF
self.gif_embed = BooleanVar()
self.gif_embed.set(False)
self.repeat = BooleanVar()
self.repeat.set(True)
self.perfield_var = BooleanVar()
self.perfield_var.set(False)
self.fps = IntVar()
self.fps.set(fps_config)
# Levels
self.gamma = DoubleVar()
self.gamma.set(1.0)
# Frames visibility
self.save_image_frame = BooleanVar()
self.save_image_frame.set(True)
self.image_levels_frame = BooleanVar()
self.image_levels_frame.set(True)
self.save_animation_frame = BooleanVar()
self.save_animation_frame.set(True)
self.frame_scale_frame = BooleanVar()
self.frame_scale_frame.set(False)
self.old_animation_frame = BooleanVar()
self.old_animation_frame.set(True)
# Fast image change flag
self.fast_img_change = False
# shower info, when available
self.meteor_info = []
self.current_img_timestamp = None
# Misc
global readFF
readFF = self.readFF_decorator(readFF) # Decorate readFF function by also passing datatype, so that readFF doesn't have to be changed through the code
# Initilize GUI
self.initUI()
# Bind key presses, window changes, etc. (key bindings)
parent.bind("<Home>", self.move_top)
parent.bind("<End>", self.move_bottom)
# Call default bindings
self.defaultBindings()
parent.bind("<Left>", self.filter_left)
parent.bind("<Right>", self.filter_right)
parent.bind("<F1>", self.maxframe_set)
parent.bind("<F2>", self.colorized_set)
parent.bind("<F3>", self.detection_only_set)
parent.bind("<F4>", self.avgframe_set)
parent.bind("<F5>", self.odd_set)
parent.bind("<F6>", self.even_set_toggle)
parent.bind("<F7>", self.frame_filter_set)
if not disable_UI_video:
parent.bind("<F9>", self.video_set)
parent.bind("<Delete>", self.deinterlace_toggle)
parent.bind("<Insert>", self.hold_levels_toggle)
parent.bind("<Return>", self.copy_bin_to_sorted)
parent.bind("C", self.callConfirmationStart)
parent.bind("R", self.showRadiantMap)
# Update UI changes
parent.update_idletasks()
parent.update()
# If the directory path was given, open it
if dir_path is not None:
self.askdirectory(dir_path=dir_path)
# Run confirmation if the flag was given
if confirmation:
self.confirmationStart(ftpDetectFile=os.path.basename(ftpdetectfile))
def callConfirmationStart(self, dummy):
self.confirmationStart(ftpDetectFile='')
def showRadiantMap(self, dummy):
radmaps = glob.glob(os.path.join(self.dir_path, '*radiants.png'))
if len(radmaps) == 0:
return
radmap = radmaps[0]
im = img.open(radmap)
resize_factor = int(self.image_resize_factor.get())
if resize_factor == 0:
resize_factor = 2
im = im.resize((int(1280/resize_factor), int(720/resize_factor)))
radimage = ImageTk.PhotoImage(im)
#self.imagelabel = Label(self, image = radimage)
self.imagelabel.configure(image = radimage)
self.imagelabel.image = radimage
log.info('Showing radiant map')
return
def updateUFOData(self, ftpdata, ufoData):
newufoData = []
tstamps = []
for li in range(len(ufoData)):
if li ==0:
# skip this for now, we will add it later
pass
else:
d = ufoData[li].split(',')
ss = float(d[6])
sec = int(float(ss))
us = int((ss-sec)*1000)*1000 # avoid rounding error - data is in millisecs
# get the datetime without the seconds
thisdt = datetime.datetime(int(d[1]), int(d[2]), int(d[3]), int(d[4]), int(d[5]),0,us)
# then add on the seconds. This is to cater for seconds rounding up to 60
thisdt = thisdt + datetime.timedelta(seconds=sec)
if sys.version_info[0] >=3:
tstamps.append(thisdt.timestamp())
else:
tstamps.append((thisdt - datetime.datetime(1970, 1, 1)).total_seconds())
# use an ndarray so i can perform conditional matching
ufotype=np.dtype([('ts','f8')])
all_data = np.array(tstamps, dtype=ufotype)
for i in range(len(ftpdata)):
if i < 11:
continue
if ftpdata[i][:3]=='---':
# extract the datetime of the start of the event
file_name = ftpdata[i+1]
info_line = ftpdata[i+3]
first_frame = ftpdata[i+4]
splits = file_name.split('_')
dt = datetime.datetime.strptime(splits[2] + '_' + splits[3] + '.' + splits[4], '%Y%m%d_%H%M%S.%f')
splits = info_line.split(' ')
fps = float(splits[3])
splits = first_frame.split(' ')
addsecs = float(splits[0])/fps
addmus = int(addsecs*1000)*1000
dt = dt + datetime.timedelta(microseconds=addmus)
if sys.version_info[0] >=3:
dt = dt.timestamp()
else:
dt = (dt - datetime.datetime(1970, 1, 1)).total_seconds()
cond = abs(all_data['ts'] - dt) < 0.01 # seems to be 4-5ms variance
match = all_data[cond]
if len(match) > 0:
for ma in match:
idx = np.where(all_data == ma)
newufoData.append(ufoData[idx[0][0]+1])
tmparr = np.unique(newufoData, axis=0)
#print(newufoData, tmparr)
newufoData = np.insert(tmparr, 0, ufoData[0])
return newufoData
def defaultBindings(self):
""" Default key bindings. User for program init and resetting after confirmation is done.
"""
# Unbind possible old bindings
SuperUnbind("Delete", self, self.parent)
SuperUnbind("Prior", self, self.parent)
SuperUnbind("Next", self, self.parent)
# Go fast when pressing the key down (no image loading)
SuperBind('Up', self, self.parent, lambda: self.fast_img_on('up'), lambda: self.fast_img_off('up'))
SuperBind('Down', self, self.parent, lambda: self.fast_img_on('down'), lambda: self.fast_img_off('down'))
self.parent.bind("<Prior>", self.capturedModeSet) # Page up
self.parent.bind("<Next>", self.detectedModeSet) # Page down
self.parent.bind("<Return>", self.copy_bin_to_sorted) # Enter
self.parent.bind("<Delete>", self.deinterlace_toggle) # Deinterlace
def readFF_decorator(self, func):
""" Decorator used to pass self.data_type to readFF without changing all readFF statements in the code.
"""
def inner(*args, **kwargs):
if "datatype" in kwargs:
return func(*args, **kwargs)
else:
return func(*args, datatype = self.data_type.get())
return inner
def correct_datafile_name(self, datafile):
""" Returns True if the given string is a proper FF*.bin or Skypatrol name (depending on data type), else it returns false.
"""
if self.data_type.get() == 1:
# CAMS data type (OLD)
if len(datafile) == 37:
# e.g. FF451_20140819_003718_000_0397568.bin
if datafile.count("_") == 4:
if datafile.split('.')[-1] == 'bin':
if datafile[0:2] == "FF":
return True, 1
# CAMS data type (NEW)
if len(datafile) == 41:
# e.g. FF_000432_20161024_075333_209_0944384.bin
if datafile.count("_") == 5:
if datafile.split('.')[-1] == 'bin':
if datafile[0:2] == "FF":
return True, -1
elif self.data_type.get() == 2:
# Skypatrol data type
if len(datafile) == 12:
# e.g. 00000171.bmp
if datafile.split('.')[-1] == 'bmp':
return True, 0
else:
# FITS data type
if datafile.lower().endswith('.fits'):
if datafile.lower().startswith('ff'):
return True, -1
return False
def readConfig(self):
""" Reads the configuration file.
"""