-
Notifications
You must be signed in to change notification settings - Fork 0
/
tab_camera.py
1250 lines (1031 loc) · 58.6 KB
/
tab_camera.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
from PyQt5 import QtCore, QtWidgets, QtGui
import global_camera
from PyQt5.QtCore import pyqtSignal as Signal
import os
import threading
from queue import Queue
from config_level import Config_level
import numpy as np
import image_processing as imp
import time
#import win32api
import global_queue
class Tab_camera(QtWidgets.QWidget):
#signals
##Signal configuration change to the GUI
configuration_update = Signal(str, str, float)#name, location, duration
##Camera Control signals
send_status_msg = Signal(str, int, int)
connection_update = Signal(bool, int, str, int)#connected, state - 0=disconnected 1=standby 2=busy, camera name, camera tab
recording_update = Signal(bool, int)
preview_update = Signal(bool, int)
request_prediction = Signal(np.ndarray)
received_info = Signal(int, int)
fps_info = Signal(float, int)
def __init__(self, camIndex, prevRef):
super(Tab_camera, self).__init__()
self.preview_live = False
self.recording = False
##Holds parameter category paths for tree widget
self.top_items = {}
##Holds children widgets for tree widget
self.children_items = {}
##Flag is not set while the application is getting parameters from the cam object
self.param_flag = threading.Event()
##Flag used when running various parameter refreshing methods
self.update_flag = threading.Event()
##Flag used when running various parameter refreshing methods
self.update_completed_flag = threading.Event()
self.update_completed_flag.set()
##Used to store values of parameters when automatically refreshing them
self.parameter_values = {}
self.tab_index = 0
##Contains all dynamically created widgets for parameters
self.feat_widgets = {}
##Contains all dynamically created labels of parameters
self.feat_labels = {}
##Stores dictionaries of every parameter until they are processed to the GUI
self.feat_queue = Queue()
self.connected = False
##Widget used to transfer GUI changes from thread into the main thread while showing parameters
self.parameters_signal = QtWidgets.QLineEdit()
self.parameters_signal.textChanged.connect(self.show_parameters)
##Indexing variable
self.camIndex = camIndex
##Reference to the preview window
self.camera_preview = prevRef
##Camera control stuff
##Widget used to transfer GUI changes from thread into the main thread while updating preview
self.resize_signal = QtWidgets.QLineEdit()
self.resize_signal.textChanged.connect(self.update_img)
self.save_location = "C:/Users/PC_Bilik/Desktop/test"
self.save_filename = "img"
self.sequence_duration = 0
##Holds current frame displayed in the GUI
self.image_pixmap = None
##Width of the preview area
self.w_preview = 0
##Height of the preview area
self.h_preview = 0
##Signals that a recording was stopped, either by timer or manually
self.interrupt_flag = threading.Event()
##Current frames per second received from the camera
self.fps = 0.0
##Total sum of received frames for active camera session
self.received = 0
##Last value of the dragging in the preview area - x axis
self.move_x_prev = 0
##Last value of the dragging in the preview area - y axis
self.move_y_prev = 0
##Value of current preview zoom in %/100
self.preview_zoom = 1
##Resizing image to preview area size instead of using zoom
self.preview_fit = True
self.connected = False
self.preview_live = False
self.recording = False
self.in_process = False
self.add_widgets()
self.connect_actions()
self.set_texts()
def add_widgets(self):
self.setObjectName(u"tab_camera_1")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self)
self.verticalLayout_2.setObjectName(u"verticalLayout_2")
# Conf camera
self.conf_camera = QtWidgets.QGroupBox(self)
self.conf_camera.setObjectName(u"conf_camera")
self.gridLayout_3 = QtWidgets.QGridLayout(self.conf_camera)
self.gridLayout_3.setObjectName(u"gridLayout_3")
self.label_config_level = QtWidgets.QLabel(self.conf_camera)
self.label_config_level.setObjectName(u"label_config_level")
self.gridLayout_3.addWidget(self.label_config_level, 0, 0, 1, 1)
self.tree_features = QtWidgets.QTreeWidget(self.conf_camera)
self.tree_features.setObjectName(u"tree_features")
self.gridLayout_3.addWidget(self.tree_features, 1, 0, 1, 3)
self.btn_save_config = QtWidgets.QPushButton(self.conf_camera)
self.btn_save_config.setObjectName(u"btn_save_config")
self.gridLayout_3.addWidget(self.btn_save_config, 2, 0, 1, 2)
self.btn_load_config = QtWidgets.QPushButton(self.conf_camera)
self.btn_load_config.setObjectName(u"btn_load_config")
self.gridLayout_3.addWidget(self.btn_load_config, 2, 2, 1, 1)
self.combo_config_level = QtWidgets.QComboBox(self.conf_camera)
self.combo_config_level.addItem("")
self.combo_config_level.addItem("")
self.combo_config_level.addItem("")
self.combo_config_level.setObjectName(u"combo_config_level")
self.gridLayout_3.addWidget(self.combo_config_level, 0, 1, 1, 2)
self.verticalLayout_2.addWidget(self.conf_camera)
# Conf recording
self.conf_recording = QtWidgets.QGroupBox(self)
self.conf_recording.setObjectName(u"conf_recording")
self.gridLayout_5 = QtWidgets.QGridLayout(self.conf_recording)
self.gridLayout_5.setObjectName(u"gridLayout_5")
self.label_sequence_name = QtWidgets.QLabel(self.conf_recording)
self.label_sequence_name.setObjectName(u"label_sequence_name")
self.gridLayout_5.addWidget(self.label_sequence_name, 0, 0, 1, 4)
self.label_file_name_recording = QtWidgets.QLabel(self.conf_recording)
self.label_file_name_recording.setObjectName(u"label_file_name_recording")
self.gridLayout_5.addWidget(self.label_file_name_recording, 1, 0, 1, 1)
self.line_edit_sequence_name = QtWidgets.QLineEdit(self.conf_recording)
self.line_edit_sequence_name.setObjectName(u"line_edit_sequence_name")
self.gridLayout_5.addWidget(self.line_edit_sequence_name, 1, 1, 1, 3)
self.file_manager_save_location = QtWidgets.QPushButton(self.conf_recording)
self.file_manager_save_location.setObjectName(u"file_manager_save_location")
self.gridLayout_5.addWidget(self.file_manager_save_location, 2, 0, 1, 1)
self.line_edit_save_location = QtWidgets.QLineEdit(self.conf_recording)
self.line_edit_save_location.setObjectName(u"line_edit_save_location")
self.gridLayout_5.addWidget(self.line_edit_save_location, 2, 1, 1, 3)
self.label_sequence_duration = QtWidgets.QLabel(self.conf_recording)
self.label_sequence_duration.setObjectName(u"label_sequence_duration")
self.gridLayout_5.addWidget(self.label_sequence_duration, 3, 0, 1, 2)
self.line_edit_sequence_duration = QtWidgets.QDoubleSpinBox(self.conf_recording)
self.line_edit_sequence_duration.setObjectName(u"line_edit_sequence_duration")
self.gridLayout_5.addWidget(self.line_edit_sequence_duration, 3, 2, 1, 2)
self.label_sequence_duration_tip = QtWidgets.QLabel(self.conf_recording)
self.label_sequence_duration_tip.setObjectName(u"label_sequence_duration_tip")
self.gridLayout_5.addWidget(self.label_sequence_duration_tip, 4, 0, 1, 4)
self.btn_save_sequence_settings = QtWidgets.QPushButton(self.conf_recording)
self.btn_save_sequence_settings.setObjectName(u"btn_save_sequence_settings")
self.gridLayout_5.addWidget(self.btn_save_sequence_settings, 5, 0, 1, 3)
self.btn_reset_sequence_settings = QtWidgets.QPushButton(self.conf_recording)
self.btn_reset_sequence_settings.setObjectName(u"btn_reset_sequence_settings")
self.gridLayout_5.addWidget(self.btn_reset_sequence_settings, 5, 3, 1, 1)
self.verticalLayout_2.addWidget(self.conf_recording)
# Ctl image
self.ctl_image = QtWidgets.QGroupBox(self)
self.ctl_image.setObjectName(u"ctl_image")
self.gridLayout_9 = QtWidgets.QGridLayout(self.ctl_image)
self.gridLayout_9.setObjectName(u"gridLayout_9")
self.ctl_record = QtWidgets.QGroupBox(self.ctl_image)
self.ctl_record.setObjectName(u"ctl_record")
self.gridLayout_8 = QtWidgets.QGridLayout(self.ctl_record)
self.gridLayout_8.setObjectName(u"gridLayout_8")
self.btn_single_frame = QtWidgets.QPushButton(self.ctl_record)
self.btn_single_frame.setObjectName(u"btn_single_frame")
self.gridLayout_8.addWidget(self.btn_single_frame, 0, 0, 1, 1)
self.btn_start_recording = QtWidgets.QPushButton(self.ctl_record)
self.btn_start_recording.setObjectName(u"btn_start_recording")
self.gridLayout_8.addWidget(self.btn_start_recording, 0, 1, 1, 1)
self.btn_start_preview = QtWidgets.QPushButton(self.ctl_record)
self.btn_start_preview.setObjectName(u"btn_start_preview")
self.gridLayout_8.addWidget(self.btn_start_preview, 1, 0, 1, 1)
self.btn_start_process = QtWidgets.QPushButton(self.ctl_record)
self.btn_start_process.setObjectName(u"btn_start_process")
self.gridLayout_8.addWidget(self.btn_start_process, 1, 1, 1, 1)
self.gridLayout_9.addWidget(self.ctl_record, 0, 0, 1, 1)
self.ctl_zoom = QtWidgets.QGroupBox(self.ctl_image)
self.ctl_zoom.setObjectName(u"ctl_zoom")
self.gridLayout_6 = QtWidgets.QGridLayout(self.ctl_zoom)
self.gridLayout_6.setObjectName(u"gridLayout_6")
self.btn_zoom_in = QtWidgets.QPushButton(self.ctl_zoom)
self.btn_zoom_in.setObjectName(u"btn_zoom_in")
self.gridLayout_6.addWidget(self.btn_zoom_in, 0, 0, 1, 1)
self.btn_zoom_out = QtWidgets.QPushButton(self.ctl_zoom)
self.btn_zoom_out.setObjectName(u"btn_zoom_out")
self.gridLayout_6.addWidget(self.btn_zoom_out, 0, 1, 1, 1)
self.btn_zoom_fit = QtWidgets.QPushButton(self.ctl_zoom)
self.btn_zoom_fit.setObjectName(u"btn_zoom_fit")
self.gridLayout_6.addWidget(self.btn_zoom_fit, 1, 0, 1, 1)
self.btn_zoom_100 = QtWidgets.QPushButton(self.ctl_zoom)
self.btn_zoom_100.setObjectName(u"btn_zoom_100")
self.gridLayout_6.addWidget(self.btn_zoom_100, 1, 1, 1, 1)
self.gridLayout_9.addWidget(self.ctl_zoom, 0, 1, 1, 1)
self.verticalLayout_2.addWidget(self.ctl_image)
def connect_actions(self):
# Params
self.combo_config_level.currentIndexChanged.connect(self.load_parameters)
self.btn_save_config.clicked.connect(self.save_cam_config)
self.btn_load_config.clicked.connect(self.load_cam_config)
# Recording
self.line_edit_save_location.textChanged.connect(self.send_conf_update)
self.line_edit_sequence_duration.valueChanged.connect(self.send_conf_update)
self.line_edit_sequence_name.textChanged.connect(self.send_conf_update)
self.file_manager_save_location.clicked.connect(lambda: self.get_directory(self.line_edit_save_location))
self.btn_save_sequence_settings.clicked.connect(self.save_seq_settings)
self.btn_reset_sequence_settings.clicked.connect(self.reset_seq_settings)
# Image ctl
self.btn_zoom_out.clicked.connect(lambda: self.set_zoom(-1))
self.btn_zoom_fit.clicked.connect(lambda: self.set_zoom(0))
self.btn_zoom_in.clicked.connect(lambda: self.set_zoom(1))
self.btn_zoom_100.clicked.connect(lambda: self.set_zoom(100))
self.btn_single_frame.clicked.connect(self.single_frame)
self.btn_start_preview.clicked.connect(lambda: self.preview(False))
self.btn_start_recording.clicked.connect(self.record)
self.btn_start_process.clicked.connect(lambda: self.preview(True))
def set_texts(self):
self.conf_camera.setTitle("Configure Camera")
self.label_config_level.setText("Configuration level")
self.tree_features.headerItem().setText(0, "Feature")
self.tree_features.headerItem().setText(1, "Value")
self.btn_save_config.setText("Save Configuration")
self.btn_load_config.setText("Load Configuration")
self.combo_config_level.setItemText(0, "Beginner")
self.combo_config_level.setItemText(1, "Expert")
self.combo_config_level.setItemText(2, "Guru")
self.conf_recording.setTitle("Configure Recording")
self.label_sequence_name.setText("Tip: Use %n for sequence number, %d for date and %t for time stamp ")
self.label_file_name_recording.setText("File name")
self.file_manager_save_location.setText("Save Location")
self.label_sequence_duration.setText("Sequence duration [s]")
self.label_sequence_duration_tip.setText("Tip: Leave empty for manual control using Start/Stop recording buttons")
self.btn_save_sequence_settings.setText("Save settings")
self.btn_reset_sequence_settings.setText("Default settings")
self.ctl_image.setTitle("Image Control")
self.ctl_record.setTitle("")
self.btn_single_frame.setText("Single frame")
self.btn_start_recording.setText("Start/Stop recording")
self.btn_start_preview.setText("Start/Stop preview")
self.btn_start_process.setText("Start/Stop processing")
self.ctl_zoom.setTitle("")
self.btn_zoom_in.setText("Zoom In")
self.btn_zoom_out.setText("Zoom Out")
self.btn_zoom_fit.setText("Fit to window")
self.btn_zoom_100.setText("Zoom to 100%")
# ==============================================
# Camera control
# ==============================================
def record(self):
"""!@brief Starts and stops recording
@details Is called by start/stop button. Recording is always started
manually. Recording ends with another button click or after time set
in self.line_edit_sequence_duration passes. Save location and name is
determined by the text in self.line_edit_save_location and
self.line_edit_sequence_name.
"""
if self.connected:
if(not self.recording):
#Change status icon and print status message
self.connection_update.emit(True, 2, "-1", self.camIndex)
self.send_status_msg.emit("Starting recording", 0, self.camIndex)
self.recording_update.emit(True, self.camIndex)
self.recording = True
#Start new recording with defined name and save path
global_camera.cams.active_devices[global_camera.active_cam[self.camIndex]].start_recording(self.save_location,
self.save_filename,
'nothing')
#If automatic sequence duration is set, create thread that will
#automatically terminate the recording
if(True):#self.sequence_duration.value > 0):
self.interrupt_flag.clear()
self.seq_duration_thread = threading.Thread(target=self.seq_duration_wait)
self.seq_duration_thread.daemon = True
self.seq_duration_thread.start()
#Start live preview in a new thread
self.show_preview_thread = threading.Thread(target=self.show_preview)
self.show_preview_thread.daemon = True
self.show_preview_thread.start()
self.send_status_msg.emit("Recording",0, self.camIndex)
else:
#Set status message and standby icon
self.connection_update.emit(True, 1, "-1", self.camIndex)
self.send_status_msg.emit("Stopping recording", 0, self.camIndex)
#Tell automatic sequence duration thread to end
self.interrupt_flag.set()
#End recording
global_camera.cams.active_devices[global_camera.active_cam[self.camIndex]].stop_recording()
self.recording_update.emit(False, self.camIndex)
self.recording = False
self.preview_live = False
self.preview_update.emit(False, self.camIndex)
self.send_status_msg.emit("Recording stopped", 3500, self.camIndex)
def seq_duration_wait(self):
"""!@brief Automatic recording interrupt.
@details Let camera record for defined time and if the recording is not
manually terminated stop the recording.
"""
#wait for the first frame to be received
while global_queue.active_frame_queue[global_camera.active_cam[self.camIndex]].empty():
time.sleep(0.001)
#print status message
self.send_status_msg.emit("Recording for "+self.line_edit_sequence_duration.text()+"s started", 0, self.camIndex)
#wait either for manual recording stop or wait for defined time
self.interrupt_flag.wait(float(self.line_edit_sequence_duration.text()))
#If the recording is still running (not terminated manually), stop
#the recording.
if(self.recording):
self.record()
def preview(self, process):
"""!@brief Starts live preview
@details Unlike recording method, this method does not save frames to a
drive. Preview picture is rendered in separate thread.
"""
#continue only if camera is connected
if self.connected:
if((not self.preview_live) and (not self.in_process)):
#Set status message and icon
self.connection_update.emit(True, 2, "-1", self.camIndex)
self.preview_update.emit(True, self.camIndex)
#Start camera frame acquisition (not recording)
global_camera.cams.active_devices[global_camera.active_cam[self.camIndex]].start_acquisition()
#Create and run thread to draw frames to gui
if process:
self.send_status_msg.emit("Starting processing", 1500, self.camIndex)
self.show_preview_thread = threading.Thread(target=self.show_preview, args = [process])
self.in_process = True
else:
self.send_status_msg.emit("Starting preview", 1500, self.camIndex)
self.show_preview_thread = threading.Thread(target=self.show_preview, args = [process])
self.preview_live = True
self.show_preview_thread.daemon = True
self.show_preview_thread.start()
else:
#Reset status icon and print message
self.connection_update.emit(True, 1, "-1", self.camIndex)
#Stop receiving frames
global_camera.cams.active_devices[global_camera.active_cam[self.camIndex]].stop_acquisition()
if (not self.in_process):
self.preview_live = False
self.send_status_msg.emit("Stopping preview", 1500, self.camIndex)
else:
self.in_process = False
self.send_status_msg.emit("Stopping processing", 1500, self.camIndex)
self.preview_update.emit(False, self.camIndex)
def set_zoom(self, flag):
"""!@brief Set the zoom amount of the image previewed
@details This method only sets the zooming variable, actual resizing
is done in other methods.
@param[in] flag Is used to define type of zoom.
1 - zoom in
-1 - zoom out
0 - zoom fit
100- zoom reset
"""
#flag 1 zoom in, -1 zoom out, 0 zoom fit, 100 zoom reset
if(flag == -1 and self.preview_zoom > 0.1):
self.preview_fit = False
self.preview_zoom -= 0.1
elif(flag == 1):
self.preview_fit = False
self.preview_zoom += 0.1
elif(flag == 0):
self.preview_fit = True
elif(flag == 100):
self.preview_fit = False
self.preview_zoom = 1
def single_frame(self):
"""!@brief Acquire and draw a single frame.
@details Unlike the live preview, this method runs in the main thread
and therefore can modify frontend variables. The method may block whole
application but its execution should be fast enough to not make a
difference.
"""
#Method runs only if camera is connected
if self.connected and not(self.preview_live or self.recording):
#Set status icon and message
self.send_status_msg.emit("Receiving single frame", 1500, self.camIndex)
self.connection_update.emit(True, 2, "-1", self.camIndex)
#Get image
image, pixel_format = global_camera.cams.active_devices[global_camera.active_cam[self.camIndex]].get_single_frame()
#Try to run prediction
self.request_prediction.emit(image)
#Set up a new value of received frames in the statusbar
self.received = self.received + 1
self.received_info.emit(self.received, self.camIndex)
#Convert image to proper format fo PyQt
h, w, ch = image.shape
bytes_per_line = ch * w
image = QtGui.QImage(image.data, w, h, bytes_per_line, self._get_QImage_format(pixel_format))
#get size of preview window
w_preview = self.camera_preview.size().width()
h_preview = self.camera_preview.size().height()
image_scaled = image.scaled(w_preview,
h_preview,
QtCore.Qt.KeepAspectRatio)
#Set image to gui
self.camera_preview.resize(w_preview,
h_preview)
self.camera_preview.setPixmap(QtGui.QPixmap.fromImage(image_scaled))
self.camera_preview.show()
#Reset status icon
self.connection_update.emit(True, 1, "-1", self.camIndex)
def show_preview(self, process):
"""!@brief Draws image from camera in real time.
@details Acquires images from camera and draws them in real time at
the same rate as is display refresh_rate. If the frames come too fast,
only one at the most recent one is drawn and the rest is dumped.
"""
#Determine refresh rate of used display. This way the method will not
#run too slowly or redundantly fast.
#device = win32api.EnumDisplayDevices()
#refresh_rate = win32api.EnumDisplaySettings(device.DeviceName, -1).DisplayFrequency
refresh_rate = 30
#Auxiliary variables for fps calculation
frames = 0
cycles = 0
color_format = QtGui.QImage.Format_Invalid
str_color = None
time_fps = time.monotonic_ns()
#runs as long as the camera is recording or preview is active
while self.recording or self.preview_live:
cycles = cycles + 1
#Draw only if thre is at least 1 frame to draw
if not global_queue.active_frame_queue[global_camera.active_cam[self.camIndex]].qsize() == 0:
image = global_queue.active_frame_queue[global_camera.active_cam[self.camIndex]].get_nowait()
self.received = self.received + 1
frames += 1
#Dump all remaining frames (If frames are received faster than
#refresh_rate).
while not global_queue.active_frame_queue[global_camera.active_cam[self.camIndex]].qsize() == 0:
frames += 1
self.received = self.received + 1
global_queue.active_frame_queue[global_camera.active_cam[self.camIndex]].get_nowait()
if process:
#Try to process the image
image = imp.processImage_main(image)
#TODO: zjistit, proc se nevycita ch
h, w = image[0].shape
ch = 1
bytes_per_line = ch * w
else:
#Convert image to proper format for PyQt
h, w, ch = image[0].shape
bytes_per_line = ch * w
#Set up a new value of received frames in the statusbar
self.received_info.emit(self.received, self.camIndex)
#Change to time dependency instead of cycle#More cycles -> more exact fps calculation (value is more stable in gui)
if cycles > 30:
time_now = time.monotonic_ns()
time_passed = time_now - time_fps
time_fps = time_now
#[frames*Hz/c] -> [frames/s]
self.fps = round(frames/(time_passed/1_000_000_000),1)
self.fps_info.emit(self.fps, self.camIndex)
cycles = 0
frames = 0
if(str_color != image[1]):
str_color = image[1]
color_format = self._get_QImage_format(str_color)
if(color_format == QtGui.QImage.Format_Invalid):
self.send_status_msg.emit("Used image format is not supported", 0, self.camIndex)
image = QtGui.QImage(image[0].data, w, h, bytes_per_line, color_format)
#TODO Get color format dynamically
#get size of preview window if zoom fit is selected
if(self.preview_fit == True):
self.w_preview = self.camera_preview.size().width()
self.h_preview = self.camera_preview.size().height()
image_scaled = image.scaled(self.w_preview,
self.h_preview,
QtCore.Qt.KeepAspectRatio)
else:#else use zoom percentage
self.w_preview = w*self.preview_zoom
self.h_preview = w*self.preview_zoom
image_scaled = image.scaled(self.w_preview,
self.w_preview,
QtCore.Qt.KeepAspectRatio)
self.image_pixmap = QtGui.QPixmap.fromImage(image_scaled)
self.preview_callback()
#Set image to gui
#Wait for next display frame
time.sleep(1/refresh_rate)
#When recording stops, change fps to 0
self.fps = 0.0
self.fps_info.emit(self.fps, self.camIndex)
def preview_callback(self):
"""!@brief Auxiliary method used to transfer thread state change into
the main thread.
"""
if(self.resize_signal.text() != "A"):
self.resize_signal.setText("A")
else:
self.resize_signal.setText("B")
def eventFilter(self, obj, event):
"""!@brief Implements dragging inside preview area
@details whin user cliks and drags inside of a preview area, this
method is called and do the scrolling based on the distance dragged in
each direction.
"""
if (obj == self.camera_preview):
if(event.type() == QtCore.QEvent.MouseMove ):
if self.move_x_prev == 0:
self.move_x_prev = event.pos().x()
if self.move_y_prev == 0:
self.move_y_prev = event.pos().y()
dist_x = self.move_x_prev - event.pos().x()
dist_y = self.move_y_prev - event.pos().y()
self.camera_preview.verticalScrollBar().setValue(
self.camera_preview.verticalScrollBar().value() + dist_y)
self.camera_preview.horizontalScrollBar().setValue(
self.camera_preview.horizontalScrollBar().value() + dist_x)
#self.preview_area.scrollContentsBy(dist_x,dist_y)
self.move_x_prev = event.pos().x()
self.move_y_prev = event.pos().y()
elif event.type() == QtCore.QEvent.MouseButtonRelease:
self.last_time_move = 0
return QtWidgets.QWidget.eventFilter(self, obj, event)
def update_img(self):
"""!@brief update image in the live preview window.
@details This method must run in the main thread as it modifies frontend
data of the gui.
"""
#Resize preview label if preview window size changed
if(self.w_preview != self.camera_preview.size().width() or
self.h_preview != self.camera_preview.size().height()):
self.camera_preview.resize(self.w_preview,
self.h_preview)
#set a new image to the preview area
self.camera_preview.setPixmap(self.image_pixmap)
self.camera_preview.show()
# ==============================================
# Recording
# ==============================================
def setup_validators(self):
"""!@brief create input constrains for various widgets
@details if a text widget needs certain input type, the validators are
set up here. For example setting prohibited characters of the file saved. Not used yet!
"""
self.line_edit_sequence_duration.setValidator(QtGui.QDoubleValidator(0,16777216,5))
expression = QtCore.QRegExp("^[^\\\\/:*?\"<>|]*$")
self.line_edit_sequence_name.setValidator(QtGui.QRegExpValidator(expression))
def reset_seq_settings(self):
"""!@brief Restores default recording settings
@details Settings are saved to config.ini file. Defaults are hard-coded
in this method.
"""
file_contents = []
#Open config file and load its contents
with open("config.ini", 'r') as config:
file_contents = config.readlines()
end_of_rec_conf = None
#Find end of Recording config part of the file
#if no delimiter is found a new one is added
try:
end_of_rec_conf = file_contents.index("CTI_FILES_PATHS\n")
except(ValueError):
file_contents.append("CTI_FILES_PATHS\n")
end_of_rec_conf = -1
with open("config.ini", 'w') as config:
#Write default states to the file
config.write("RECORDING\n")
config.write("filename=img(%n)\n")
config.write("save_location=Recording\n")
#maybe set to the documents folder
config.write("sequence_duration=0\n")
#When at the end of recording config part, just copy the rest of
#the initial file.
if(end_of_rec_conf):
for line in file_contents[end_of_rec_conf:]:
config.write(line)
# TODO: zeptat se
#Fill the Recording tab with updated values
self.load_config("img(%n)", "Recording", "0")
#Print status msg
self.send_status_msg.emit("Configuration restored", 2500, self.camIndex)
def save_seq_settings(self):
"""!@brief Saves recording settings
@details Settings are saved to config.ini file. Parameters saved are:
file name, save, location and sequence duration.
"""
file_contents = []
#Open config file and load its contents
with open("config.ini", 'r') as config:
file_contents = config.readlines()
#Open config file for writing
with open("config.ini", 'w') as config:
for line in file_contents:
#Reading configuration for recording
if(line.startswith("filename=")):
config.write("filename=" + self.line_edit_sequence_name.text() + "\n")
elif(line.startswith("save_location=")):
config.write("save_location=" + self.line_edit_save_location.text() + "\n")
elif(line.startswith("sequence_duration=")):
config.write("sequence_duration=" + self.line_edit_sequence_duration.text() + "\n")
else:
#All content not concerning recording is written back without change
config.write(line)
self.send_status_msg.emit("Configuration saved", 0, self.camIndex)
def load_config(self, filename=None , save_location=None, sequence_duration=None):
"""!@brief Fills in saved values for recording configuration
@param[in] filename Template for naming saved files
@param[in] save_location Where should the images be saved
@param[in] sequence_duration Length of a recording sequence
"""
try:
sequence_duration = float(sequence_duration)
except ValueError:
sequence_duration = 0
if(filename):
self.line_edit_sequence_name.setText(filename)
if(save_location):
self.line_edit_save_location.setText(save_location)
if(sequence_duration):
self.line_edit_sequence_duration.setValue(sequence_duration)
def get_directory(self, line_output = None):
"""!@brief Opens file dialog for user to set path to save frames.
@details Method is called by Save Location button. Path is written to
the label next to the button and can be further modified.
"""
#Open file dialog for choosing a folder
name = QtWidgets.QFileDialog.getExistingDirectory(self,
"Select Folder",
)
#Set label text to chosen folder path
if(line_output):
line_output.setText(name)
return name
def send_conf_update(self):
"""!@brief Used to emit configuration update signal based on current values of line edits"""
self.configuration_update.emit(self.line_edit_sequence_name.text(),
self.line_edit_save_location.text(),
self.line_edit_sequence_duration.value())
# ==============================================
# Camera
# ==============================================
def show_parameters(self):
"""!@brief Loads all camera's features and creates dynamic widgets for
every feature.
@details This method is called when user first enters parameters tab or
when the configuration level changes. All the widgets are created dynamically
and based on the type of the feature, proper widget type is selected. Also
these widgets have method to change their value associated with them
when created.
"""
num = 0
categories = []
self.top_items = {}
self.children_items = {}
self.tree_features.clear()
for name in self.feat_widgets:
self.feat_widgets[name].deleteLater()
for name in self.feat_labels:
self.feat_labels[name].deleteLater()
self.feat_widgets.clear()
self.feat_labels.clear()
while not self.feat_queue.empty():
try:
param = self.feat_queue.get()
param['attr_cat'] = param['attr_cat'].lstrip('/')
ctgs = param['attr_cat'].split('/')
for i, ctg in enumerate(ctgs):
if(not(ctg in categories)):
if(i == 0):
self.top_items[ctg] = QtWidgets.QTreeWidgetItem([ctg])
self.tree_features.addTopLevelItem(self.top_items[ctg])
else:
self.top_items[ctg] = QtWidgets.QTreeWidgetItem([ctg])
self.top_items[ctgs[i-1]].addChild(self.top_items[ctg])
categories.append(ctg)
#Create a new label with name of the feature
self.feat_labels[param["name"]] = QtWidgets.QLabel(self)
self.feat_labels[param["name"]].setObjectName(param["name"])
self.feat_labels[param["name"]].setText(param["attr_name"])
#If the feature has a tooltip, set it.
try:
self.feat_labels[param["name"]].setToolTip(param["attr_tooltip"])
except:
pass
#Place the label on the num line of the layout
#self.parameters_layout.setWidget(num, QtWidgets.QFormLayout.LabelRole, self.feat_labels[param["name"]])
#If the feature does not have a value, set it to 0
if param["attr_value"] == None:
param["attr_value"] = 0
#Based on the feature type, right widget is chosen to hold the
#feature's value
if param["attr_type"] == "IntFeature":
#For int feature a Line edit field is created, but only
#integers can be written in.
self.feat_widgets[param["name"]] = QtWidgets.QSpinBox(self)
if(param["attr_range"]):
self.feat_widgets[param["name"]].setRange(
param["attr_range"][0],
param["attr_range"][1])
#Set text to the current value of the feature
self.feat_widgets[param["name"]].setValue(param["attr_value"])
#Call feature change for this feature when enter is pressed in this field.
#Text is the value that will be set to the feature.
self.feat_widgets[param["name"]].valueChanged.connect(lambda new_val,param=param: global_camera.cams.active_devices[global_camera.active_cam[self.camIndex]].set_parameter(param["name"],new_val))
elif param["attr_type"] == "FloatFeature":
#For float feature a Line edit field is created, but only
#real numbers can be written in.
self.feat_widgets[param["name"]] = QtWidgets.QDoubleSpinBox(self)
if(param["attr_range"]):
self.feat_widgets[param["name"]].setRange(
param["attr_range"][0],
param["attr_range"][1])
#Set text to the current value of the feature
self.feat_widgets[param["name"]].setValue(param["attr_value"])
#Call feature change for this feature when enter is pressed in this field.
#Text is the value that will be set to the feature.
self.feat_widgets[param["name"]].valueChanged.connect(lambda new_val,param=param: global_camera.cams.active_devices[global_camera.active_cam[self.camIndex]].set_parameter(param["name"],new_val))
elif param["attr_type"] == "StringFeature":
#For string feature a Line edit field is created.
self.feat_widgets[param["name"]] = QtWidgets.QLineEdit(self)
#Set text to the current value of the feature
self.feat_widgets[param["name"]].setText(param["attr_value"])
#Call feature change for this feature when enter is pressed in this field.
#Text is the value that will be set to the feature.
self.feat_widgets[param["name"]].returnPressed.connect(lambda new_val,param=param: global_camera.cams.active_devices[global_camera.active_cam[self.camIndex]].set_parameter(param["name"],new_val))
elif param["attr_type"] == "BoolFeature":
#For bool feature a checkbox is created.
self.feat_widgets[param["name"]] = QtWidgets.QCheckBox(self)
#If value is true the checkbox is ticked otherwise remains empty
self.feat_widgets[param["name"]].setChecked(param["attr_value"])
#When state of the checkbox change, the feature is sent to
#the camera and changed to the new state
self.feat_widgets[param["name"]].stateChanged.connect(lambda new_val,param=param: global_camera.cams.active_devices[global_camera.active_cam[self.camIndex]].set_parameter(param["name"],new_val))
elif param["attr_type"] == "EnumFeature":
#For enum feature a combo box is created.
self.feat_widgets[param["name"]] = QtWidgets.QComboBox(self)
#All available enum states are added as options to the
#combo box.
for enum in param["attr_enums"]:
self.feat_widgets[param["name"]].addItem(str(enum))
#Search the options and find the index of the active value
index = self.feat_widgets[param["name"]].findText(str(param["attr_value"]), QtCore.Qt.MatchFixedString)
#Set found index to be the active one
if index >= 0:
self.feat_widgets[param["name"]].setCurrentIndex(index)
#When different option is selected change the given enum in
#the camera
self.feat_widgets[param["name"]].activated.connect(lambda new_val,param=param: global_camera.cams.active_devices[global_camera.active_cam[self.camIndex]].set_parameter(param["name"],new_val+1))
elif param["attr_type"] == "CommandFeature":
#If the feature type is not recognized, create a label with
#the text error
self.feat_widgets[param["name"]] = QtWidgets.QPushButton(self)
self.feat_widgets[param["name"]].setText("Execute command")
self.feat_widgets[param["name"]].clicked.connect(lambda val,param=param: global_camera.cams.active_devices[global_camera.active_cam[self.camIndex]].execute_command(param["name"]))
else:
#If the feature type is not recognized, create a label with
#the text error
self.feat_widgets[param["name"]] = QtWidgets.QLabel(self)
self.feat_widgets[param["name"]].setText("Unknown feature type")
self.feat_widgets[param["name"]].setEnabled(param["attr_enabled"])
#Add newly created widget to the layout on the num line
new_item = QtWidgets.QTreeWidgetItem(self.top_items[ctgs[-1]] ,['', ''])
#add new item to the last subcategory of its category tree
self.tree_features.setItemWidget(new_item, 0,self.feat_labels[param["name"]])
self.tree_features.setItemWidget(new_item, 1,self.feat_widgets[param["name"]])
#new_item = QtWidgets.QTreeWidgetItem(self.top_items[param['attr_cat']] ,[self.feat_labels[param["name"]], self.feat_widgets[param["name"]]])
self.children_items[param["name"]] = new_item
#self.parameters_layout.setWidget(num, QtWidgets.QFormLayout.FieldRole, self.feat_widgets[param["name"]])
num += 1
except:
pass
#we'll get here when queue is empty
self.param_flag.clear()
def start_refresh_parameters(self):
"""!@brief Called automatically when feat_refresh_timer runs out
@details used to start a thread to refresh parameters values. Not
called by user but automatically.
"""
#called every 4 seconds
if (self.feat_widgets and self.connected and self.tab_index == 1 and
not(self.preview_live or self.recording) and
not self.param_flag.is_set() and self.update_completed_flag.is_set()):
self.update_completed_flag.clear()
self.update_thread = threading.Thread(target=self.get_new_val_parameters)
self.update_thread.daemon = True
self.update_thread.start()
def get_new_val_parameters(self):
"""!@brief Check for new parameter value
@details after camera features are loaded, this method periodically
calls for the most recent value of each parameter.
"""
if(not self.feat_widgets):
self.update_completed_flag.set()
return
params = Queue()
tries = 0
while(tries <= 10):
if(global_camera.cams.active_devices[global_camera.active_cam[self.camIndex]].get_parameters(params,
threading.Event(),
self.combo_config_level.currentIndex()+1)):
break
else:
tries += 1
if(tries >= 10):
self.update_completed_flag.set()
return
while(not params.empty()):
parameter = params.get()
if(not(self.preview_live or self.recording) and
self.tab_index == 1):