-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1915 lines (1742 loc) · 116 KB
/
main.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 PyQt6.QtWidgets import QApplication, QMainWindow, QMessageBox, QFileDialog, QApplication, QPushButton, QVBoxLayout, QLabel, QDialog, QWidget, QVBoxLayout, QGraphicsDropShadowEffect, QSizePolicy
from PyQt6.uic import loadUi
from PyQt6.QtCore import pyqtSignal, Qt, QPropertyAnimation, QSize, QTimer, QThread, QMetaObject, Q_ARG, Qt, QObject, pyqtSignal, QFile, QIODevice
from PyQt6.QtGui import QImage, QPixmap, QIcon, QCloseEvent, QAction, QKeySequence, QShortcut, QPalette, QColor, QMovie, QGuiApplication
import numpy as np
import threading
import subprocess
import datetime
import time
import os
import sys
import cv2
import configparser
import tempfile
os.chdir(os.path.dirname(os.path.abspath(__file__)))
config = configparser.ConfigParser()
config.read('config.ini') # Replace 'config.ini' with the path to your configuration file
#Global Variables
calib_camera_enabled = False
loadingcompleted = False
log_file_content = None
global USE_TWO_CAMERAS
# CONFIG GLOBAL VARIABLES
USE_TWO_CAMERAS = config.getboolean('CAMERA_CONFIG', 'USE_TWO_CAMERAS')
CAMERA_INDEX_LEFT = config.getint('CAMERA_CONFIG', 'CAMERA_INDEX_LEFT') # Camera index for the left camera (if using two cameras)
CAMERA_INDEX_RIGHT = config.getint('CAMERA_CONFIG', 'CAMERA_INDEX_RIGHT')
DETECTIONMODE = config.getint('DETECTION_CONFIG', 'DETECTIONMODE_VALUE')
MICROCONTROLLER_PORT = config.get("IO_CONFIG", "microcontroller_port")
def imports():
# ============ IMPORTS ============
loading_splash.loading_label.setText("A Carregar: Modelos")
global FrameProcessor, AppleIndexation, LOG_FILE_PATH # Make these variables global
import modules.FrameProcessor as FrameProcessor
from modules.code_v1 import LOG_FILE_PATH
import modules.AppleIndexation as AppleIndexation
loading_splash.loading_label.setText("A Carregar: UI")
# ============= \\-// =============
class MyApp(QMainWindow): # GUI CLASS
def __init__(self): # CONSTRUCTOR
super (MyApp, self).__init__()
loadUi('ui/app.ui', self)
self.icon = QIcon('ui/icons/apple.ico')
app.setWindowIcon(self.icon)
self.configpath = 'config.ini'
# ============ INICIALIZAÇÃO COM OS VALORES DA CONFIG ============
self.mode_COMBOBOX.setCurrentIndex(config.getint('DETECTION_CONFIG', 'mode_value'))
self.detectionmode_COMBOBOX.setCurrentIndex(config.getint('DETECTION_CONFIG', 'detectionmode_value'))
self.categorizationmode_COMBOBOX.setCurrentIndex(config.getint('DETECTION_CONFIG', 'categorizationmode_value'))
self.cam2_RADIOBT.setChecked(config.getboolean('CAMERA_CONFIG', 'use_two_cameras'))
if DETECTIONMODE in [-1, 0, 1]:
self.threshold1_SLIDER.setValue(config.getint('DETECTION_CONFIG', 'threshold1_value'))
self.threshold2_SLIDER.setValue(config.getint('DETECTION_CONFIG', 'threshold2_value'))
elif DETECTIONMODE == 2:
self.threshold1_SLIDER.setValue(config.getint('CUSTOM_DETECTION_CONFIG', 'threshold1_value'))
self.threshold2_SLIDER.setValue(config.getint('CUSTOM_DETECTION_CONFIG', 'threshold2_value'))
# ============================= \\-// ============================
# ============ BINDS ============
self.upload_BT.clicked.connect(self.load_file)
self.start_BT.setShortcut(QKeySequence.fromString("I"))
self.start_BT.clicked.connect(self.start_cameracapture)
self.upload_BT.setShortcut(QKeySequence.fromString("A"))
self.reset_BT.setShortcut(QKeySequence.fromString("Ctrl+R"))
self.reset_BT.clicked.connect(self.resetapplecount)
self.nextframe_BT.clicked.connect(self.nextframe)
self.colorfilters_BT.clicked.connect(self.colorfilters_open)
self.colorfilters_BT.setShortcut(QKeySequence.fromString("F"))
self.actionOpen_Upload.setShortcuts([QKeySequence.fromString("Ctrl+O"), QKeySequence.fromString("Ctrl+A")])
self.actionOpen_Upload.triggered.connect(self.load_file)
self.actionSave_Output_File.triggered.connect(self.save_file)
self.actionSave_Output_File.setShortcuts([QKeySequence.fromString("Ctrl+S"), QKeySequence.fromString("Ctrl+G")])
self.actionSave_Frame.triggered.connect(self.save_frame)
self.actionSave_Frame.setShortcut("Ctrl+F")
self.action_small_view.triggered.connect(self.small_vw)
self.action_big_view.triggered.connect(self.big_vw)
self.action_operatorview.triggered.connect(self.operator_vw)
self.action_small_view.setShortcut("Ctrl+Left")
self.action_big_view.setShortcut("Ctrl+Right")
self.action_operatorview.setShortcuts([QKeySequence.fromString("Ctrl+End"), QKeySequence.fromString("Ctrl+1")])
self.action_calibratecamera.triggered.connect(self.calibratecamera)
self.action_calibratecamera.setShortcut("Ctrl+Shift+C")
self.action_restartprogram.triggered.connect(self.restartprogram)
self.action_restartprogram.setShortcut("Ctrl+Shift+R")
#self.menuLogs.aboutToShow.connect(self.logs_open)
#self.shortcut = QShortcut(QKeySequence('Ctrl+L'), self)
#self.shortcut.activated.connect(self.logs_open)
self.action_settings_open.triggered.connect(self.settings_open)
self.action_settings_open.setShortcut("Ctrl+D")
self.action_logs_open.triggered.connect(self.logs_open)
self.action_logs_export.triggered.connect(self.logs_save)
self.action_logs_open.setShortcut("Ctrl+L")
self.action_logs_export.setShortcut("Ctrl+Shift+L")
self.menuInfo.aboutToShow.connect(self.info_open)
self.threshold1_SLIDER.valueChanged.connect(self.update_config)
self.threshold2_SLIDER.valueChanged.connect(self.update_config)
self.mode_COMBOBOX.currentIndexChanged.connect(self.update_config)
self.detectionmode_COMBOBOX.currentIndexChanged.connect(self.detectionmode_changed)
self.categorizationmode_COMBOBOX.currentIndexChanged.connect(self.update_config)
self.cam1_RADIOBT.toggled.connect(self.update_config)
self.cam2_RADIOBT.toggled.connect(self.update_config)
# Create shortcuts to move up and down in the tabs
shortcut_up = QKeySequence.fromString("Ctrl+Up")
shortcut_down = QKeySequence.fromString("Ctrl+Down")
# Connect the shortcuts to custom slot functions
self.createShortcut(shortcut_up, self.moveTabUp)
self.createShortcut(shortcut_down, self.moveTabDown)
# Other Things
self.AverageDiameter_TextEdit.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.FalsePositives_TextEdit.setAlignment(Qt.AlignmentFlag.AlignCenter)
# ============ \\-// ============
self.videoplaying = False
self.camopen = False
self.thread_stop_flag = False
self.stop_recording_tag = False
self.filename = str()
self.showframescontinuously = True
global currentimageframe
global currentimageframe2
global videoplaying
currentimageframe = None
currentimageframe2 = None
self.video_writer = None
self.video_writer2 = None
# ============ \\-// ============
self.logFileReader = LogFileReader()
self.logFileReader.logUpdated.connect(self.updateLogText)
self.readLogFile()
def readLogFile(self):
self.logFileReader.readLogFile()
def updateLogText(self, content):
current_content = self.Log_textBrowser.toPlainText()
if content != current_content:
self.Log_textBrowser.setPlainText(content)
def createShortcut(self, key_sequence, slot_function):
shortcut = key_sequence
action = QAction(self)
action.setShortcut(shortcut)
action.triggered.connect(slot_function)
self.addAction(action)
def moveTabUp(self):
current_index = self.big_view_tabwidget.currentIndex()
new_index = (current_index + 1) % self.big_view_tabwidget.count()
self.big_view_tabwidget.setCurrentIndex(new_index)
def moveTabDown(self):
current_index = self.big_view_tabwidget.currentIndex()
new_index = current_index - 1 if current_index > 0 else self.big_view_tabwidget.count() - 1
self.big_view_tabwidget.setCurrentIndex(new_index)
def load_file(self): #FUNCTION TO OPEN THE IMAGE SELECTOR AND SELECT THE IMAGE
if self.videoplaying:
self.show_warning("Está a ser processado vídeo: Carregue PARAR (P) ou feche a App.")
else:
self.filename = QFileDialog.getOpenFileName(
filter = "Ficheiros Suportados (*.jpg *.jpeg *.png *.bmp *.tiff *.tif *.gif *.pbm *.pgm *.ppm *.xbm *.xpm *.sr *.webp *.avi *.mov *.mp4 *.mkv *.wmv *.flv *.3gp *.asf *.mpg *.rm);;Ficheiros de Imagem (*.jpg *.jpeg *.png *.bmp *.tiff *.tif *.gif *.pbm *.pgm *.ppm *.xbm *.xpm *.sr *.webp);;Ficheiros de Vídeo (*.avi *.mov *.mp4 *.mkv *.wmv *.flv *.3gp *.asf *.mpg *.rm);;Todos os Ficheiros (*)")[0]
if len(self.filename)!=0:
self.image = cv2.imread(self.filename)
if self.image is not None:
self.hsv = cv2.cvtColor(self.image, cv2.COLOR_BGR2HSV)
image = cv2.cvtColor(self.hsv, cv2.COLOR_HSV2RGB)
self.set_image(image)
self.current_type = "image"
else:
print("Processamento de Frames Iniciado")
self.nextframe_BT.setShortcut(QKeySequence.fromString("N"))
threading.Thread(target=self.video_processing_thread, args=(self.filename,)).start()
def set_image(self, image): #FUNCTION TO PUT THE INPUT IMAGE IN THE FRAME
if len(self.filename)!=0:
with open(LOG_FILE_PATH, 'a') as log:
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log.write(f"{timestamp} - Processamento de imagem iniciado\n")
# ============= OLD RESIZE CODE TO FIT THE IMAGE ============ →→→→→→→→→→→→ frame = imutils.resize(image, width=self.inputframe_1.width, height=self.inputframe_1.height)
self.progressBar.setValue(100) #RESET PROGRESSBAR
#Preview the input filters
image = FrameProcessor.ApplyInputFilters(image, customdetectionfilter)
# ========= CALCULATIONS TO KEEP IMAGE ASPECT RATIO =========
width_scalei = int(self.inputframe_1.width()) / image.shape[1]
height_scalei = int(self.inputframe_1.height()) / image.shape[0]
scalei = min(width_scalei, height_scalei)
framei = cv2.resize(image, (int(image.shape[1] * scalei), int(image.shape[0] * scalei)))
# ======== CALCULATIONS TO KEEP IMAGE ASPECT RATIO 2 ========
width_scale2i = int(self.inputframe_3.width()) / image.shape[1]
height_scale2i = int(self.inputframe_3.height()) / image.shape[0]
scale2i = min(width_scale2i, height_scale2i)
frame2i = cv2.resize(image, (int(image.shape[1] * scale2i), int(image.shape[0] * scale2i)))
# ====================== CENTER THE IMAGE ======================
emptyframei = np.full((self.inputframe_1.height(), self.inputframe_1.width(), 3), (255, 255, 255), dtype=np.uint8) # Create an empty frame with the frame dimensions
x_offseti = (self.inputframe_1.width() - framei.shape[1]) // 2
y_offseti = (self.inputframe_1.height() - framei.shape[0]) // 2
emptyframei[y_offseti:y_offseti+framei.shape[0], x_offseti:x_offseti+framei.shape[1]] = framei # Paste the resized image onto the empty frame
# ====================== CENTER THE IMAGE ======================
emptyframe2i = np.full((self.inputframe_3.height(), self.inputframe_3.width(), 3), (255, 255, 255), dtype=np.uint8) # Create an empty frame with the frame dimensions
x_offset2i = (self.inputframe_3.width() - frame2i.shape[1]) // 2
y_offset2i = (self.inputframe_3.height() - frame2i.shape[0]) // 2
emptyframe2i[y_offset2i:y_offset2i+frame2i.shape[0], x_offset2i:x_offset2i+frame2i.shape[1]] = frame2i
# ==================== CONVERT IMAGE FORMAT ====================
# ======================= UPDATE THE GUI =======================
imagef = QImage(emptyframei, emptyframei.shape[1],emptyframei.shape[0], emptyframei.strides[0],QImage.Format.Format_RGB888)
imagef2 = QImage(emptyframe2i, emptyframe2i.shape[1],emptyframe2i.shape[0], emptyframe2i.strides[0],QImage.Format.Format_RGB888)
self.inputframe_1.setPixmap(QPixmap.fromImage(imagef))
self.inputframe_3.setPixmap(QPixmap.fromImage(imagef2))
# =========================== \\--// ===========================
if self.detectionmode_COMBOBOX.currentIndex() in [-1, 0, 1, 2]:
processedimage = FrameProcessor.ImageProcessor(self.filename, image, self.detectionmode_COMBOBOX.currentIndex(), self.categorizationmode_COMBOBOX.currentIndex(), self.threshold1_SLIDER.value(), self.threshold2_SLIDER.value(), filter, customdetectionfilter)
if not processedimage[0]:
self.show_warning(processedimage[1])
else:
# get current frame and save it as a variable
imagewithfilters = FrameProcessor.ApplyFilters(processedimage[1], filter)
self.currentframesaver(imagewithfilters)
# ===================== CENTER THE IMAGE =====================
framepi = cv2.resize(imagewithfilters, (framei.shape[1], framei.shape[0]))
framep2i = cv2.resize(imagewithfilters, (frame2i.shape[1], frame2i.shape[0]))
emptyframepi = np.full((self.outputframe_1.height(), self.outputframe_1.width(), 3), (255, 255, 255), dtype=np.uint8) # Create an empty frame with the frame dimensions
emptyframepi[y_offseti:y_offseti+framei.shape[0], x_offseti:x_offseti+framei.shape[1]] = framepi # Paste the resized image onto the empty frame
emptyframep2i = np.full((self.outputframe_3.height(), self.outputframe_3.width(), 3), (255, 255, 255), dtype=np.uint8) # Create an empty frame with the frame dimensions
emptyframep2i[y_offset2i:y_offset2i+frame2i.shape[0], x_offset2i:x_offset2i+frame2i.shape[1]] = framep2i # Paste the resized image onto the empty frame
# Paste the resized image onto the empty frame
# ======================== UPDATE THE GUI ========================
imagepi = QImage(emptyframepi, emptyframepi.shape[1],emptyframepi.shape[0], emptyframepi.strides[0],QImage.Format.Format_RGB888)
imagep2i = QImage(emptyframep2i, emptyframep2i.shape[1],emptyframep2i.shape[0], emptyframep2i.strides[0],QImage.Format.Format_RGB888)
self.outputframe_1.setPixmap(QPixmap.fromImage(imagepi))
self.outputframe_5.setPixmap(QPixmap.fromImage(imagepi))
self.outputframe_3.setPixmap(QPixmap.fromImage(imagep2i))
# ============================ \\--// ============================
else:
imagewithfilters = FrameProcessor.ApplyFilters(image, filter)
self.currentframesaver(imagewithfilters)
framepf = cv2.resize(imagewithfilters, (framei.shape[1], framei.shape[0]))
framep2f = cv2.resize(imagewithfilters, (frame2i.shape[1], frame2i.shape[0]))
emptyframepf = np.full((self.outputframe_1.height(), self.outputframe_1.width(), 3), (255, 255, 255), dtype=np.uint8) # Create an empty frame with the frame dimensions
emptyframepf[y_offseti:y_offseti+framei.shape[0], x_offseti:x_offseti+framei.shape[1]] = framepf # Paste the resized image onto the empty frame
emptyframep2f = np.full((self.outputframe_3.height(), self.outputframe_3.width(), 3), (255, 255, 255), dtype=np.uint8) # Create an empty frame with the frame dimensions
emptyframep2f[y_offset2i:y_offset2i+frame2i.shape[0], x_offset2i:x_offset2i+frame2i.shape[1]] = framep2f # Paste the resized image onto the empty frame
# Paste the resized image onto the empty frame
# ======================== UPDATE THE GUI ========================
imagepf = QImage(emptyframepf, emptyframepf.shape[1],emptyframepf.shape[0], emptyframepf.strides[0],QImage.Format.Format_RGB888)
imagep2f = QImage(emptyframep2f, emptyframep2f.shape[1],emptyframep2f.shape[0], emptyframep2f.strides[0],QImage.Format.Format_RGB888)
self.outputframe_1.setPixmap(QPixmap.fromImage(imagepf))
self.outputframe_5.setPixmap(QPixmap.fromImage(imagepf))
self.outputframe_3.setPixmap(QPixmap.fromImage(imagep2f))
# ======= START AND CLOSE FUNCTIONS =======
def restartprogram(self):
python = sys.executable
os.execl(python, python, *sys.argv)
def calibratecamera(self):
global calib_camera_enabled
if not self.camopen:
self.show_warning('Inicie a captura da câmara para calibrar.')
else:
if calib_camera_enabled:
FrameProcessor.calibratecamerabool(False)
calib_camera_enabled = False
self.action_calibratecamera.setText('Calibrar Câmara (Ctrl+Shift+C)')
else:
FrameProcessor.calibratecamerabool(True)
calib_camera_enabled = True
self.action_calibratecamera.setText('Parar Calibração (Ctrl+Shift+C)')
def closeEvent(self, event: QCloseEvent):
self.thread_stop_flag = True
self.stop_recording_tag = True
self.colorfilters = ColorFilters()
self.colorfilters.close() #close filters widget when mainwindow closes
self.inputfilters = InputFilters()
self.inputfilters.close() #close filters widget when mainwindow closes
def video_processing_thread(self, filename):
self.set_video(filename)
def cameracapture_to_gui_thread(self):
self.cameracapture_to_gui()
def recording_thread(self):
self.frame_record()
# ========================== \\--// ==========================
def set_video(self, video):
cap = cv2.VideoCapture(video)
if not cap.isOpened():
self.show_warning("Falha ao abrir o ficheiro de vídeo.")
else:
self.start_stop_recording("stop")
self.start_stop_recording("start")
self.modify_startbutton("parar")
# Getting video informations for progressbar
self.total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# Create a VideoCapture object
with open(LOG_FILE_PATH, 'a') as log:
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log.write(f"{timestamp} - Processamento de vídeo iniciado\n")
while not self.thread_stop_flag:
ret, frame = cap.read()
if not ret:
break # Break the loop at the end of the video
self.videoplaying = True #bool to stop uploads while playing
global videoplaying
videoplaying = self.videoplaying
# Getting video informations for progressbar
current_frame = int(cap.get(cv2.CAP_PROP_POS_FRAMES))
progress = (current_frame / self.total_frames) * 100
self.progressBar.setValue(int(progress))
#Preview the input filters
frame = FrameProcessor.ApplyInputFilters(frame, customdetectionfilter)
# Calculate the scale and apply resizing
self.hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
frame = cv2.cvtColor(self.hsv, cv2.COLOR_HSV2RGB)
processoriginalquality = frame
width_scale = int(self.inputframe_1.width()) / frame.shape[1]
height_scale = int(self.inputframe_1.height()) / frame.shape[0]
scale = min(width_scale, height_scale)
frame = cv2.resize(frame, (int(frame.shape[1] * scale), int(frame.shape[0] * scale)))
#Calculate the scale and apply resizing 2
width_scale2 = int(self.inputframe_3.width()) / frame.shape[1]
height_scale2 = int(self.inputframe_3.height()) / frame.shape[0]
scale2 = min(width_scale2, height_scale2)
frame2 = cv2.resize(frame, (int(frame.shape[1] * scale2), int(frame.shape[0] * scale2)))
# Center the image
emptyframe = np.full((self.inputframe_1.height(), self.inputframe_1.width(), 3), (255, 255, 255), dtype=np.uint8)
x_offset = (self.inputframe_1.width() - frame.shape[1]) // 2
y_offset = (self.inputframe_1.height() - frame.shape[0]) // 2
emptyframe[y_offset:y_offset + frame.shape[0], x_offset:x_offset + frame.shape[1]] = frame
# Center the image 2
emptyframe2 = np.full((self.inputframe_3.height(), self.inputframe_3.width(), 3), (255, 255, 255), dtype=np.uint8)
x_offset2 = (self.inputframe_3.width() - frame2.shape[1]) // 2
y_offset2 = (self.inputframe_3.height() - frame2.shape[0]) // 2
emptyframe2[y_offset2:y_offset2 + frame2.shape[0], x_offset2:x_offset2 + frame2.shape[1]] = frame2
# Convert image format
image = QImage(emptyframe, emptyframe.shape[1], emptyframe.shape[0], emptyframe.strides[0], QImage.Format.Format_RGB888)
image2 = QImage(emptyframe2, emptyframe2.shape[1], emptyframe2.shape[0], emptyframe2.strides[0], QImage.Format.Format_RGB888)
# Update the GUI
self.inputframe_1.setPixmap(QPixmap.fromImage(image))
self.inputframe_3.setPixmap(QPixmap.fromImage(image2))
if self.detectionmode_COMBOBOX.currentIndex() in [-1, 0, 1, 2]:
#frame processing
processor_result = FrameProcessor.VideoProcessor(video, processoriginalquality, self.detectionmode_COMBOBOX.currentIndex(), self.categorizationmode_COMBOBOX.currentIndex(), self.threshold1_SLIDER.value(), self.threshold2_SLIDER.value(), filter, customdetectionfilter)
if not processor_result[0]:
self.show_warning(processor_result[1])
else:
# Ensure that processedvideoframe has the same dimensions as the target area
imagewithfilters = FrameProcessor.ApplyFilters(processor_result[1], filter)
processedvideoframe = cv2.resize(imagewithfilters, (frame.shape[1], frame.shape[0]))
processedvideoframe2 = cv2.resize(imagewithfilters, (frame2.shape[1], frame2.shape[0]))
# Create an empty frame with the target dimensions
emptyframep = np.full((self.outputframe_1.height(), self.outputframe_1.width(), 3), (255, 255, 255), dtype=np.uint8)
emptyframep2 = np.full((self.outputframe_3.height(), self.outputframe_3.width(), 3), (255, 255, 255), dtype=np.uint8)
# Paste the resized frame onto the target area in emptyframep
emptyframep[y_offset:y_offset + frame.shape[0], x_offset:x_offset + frame.shape[1]] = processedvideoframe
emptyframep2[y_offset2:y_offset2 + frame2.shape[0], x_offset2:x_offset2 + frame2.shape[1]] = processedvideoframe2
# Convert image format
videoframep = QImage(emptyframep, emptyframep.shape[1], emptyframep.shape[0], emptyframep.strides[0], QImage.Format.Format_RGB888)
videoframep2 = QImage(emptyframep2, emptyframep2.shape[1], emptyframep2.shape[0], emptyframep2.strides[0], QImage.Format.Format_RGB888)
# Update the GUI
if self.showframescontinuously or self.nextframebool:
self.outputframe_1.setPixmap(QPixmap.fromImage(videoframep))
self.outputframe_5.setPixmap(QPixmap.fromImage(videoframep))
self.outputframe_3.setPixmap(QPixmap.fromImage(videoframep2))
self.currentframesaver(processor_result[1]) #Save latest frame in a variable
self.nextframebool = False
else:
# Update the GUI
imagewithfilters = FrameProcessor.ApplyFilters(processoriginalquality, filter)
framepf = cv2.resize(imagewithfilters, (frame.shape[1], frame.shape[0]))
framep2f = cv2.resize(imagewithfilters, (frame2.shape[1], frame2.shape[0]))
emptyframepf = np.full((self.outputframe_1.height(), self.outputframe_1.width(), 3), (255, 255, 255), dtype=np.uint8) # Create an empty frame with the frame dimensions
emptyframepf[y_offset:y_offset+frame.shape[0], x_offset:x_offset+frame.shape[1]] = framepf # Paste the resized image onto the empty frame
emptyframep2f = np.full((self.outputframe_3.height(), self.outputframe_3.width(), 3), (255, 255, 255), dtype=np.uint8) # Create an empty frame with the frame dimensions
emptyframep2f[y_offset2:y_offset2+frame2.shape[0], x_offset2:x_offset2+frame2.shape[1]] = framep2f # Paste the resized image onto the empty frame
# Paste the resized image onto the empty frame
# ======================== UPDATE THE GUI ========================
imagepf = QImage(emptyframepf, emptyframepf.shape[1],emptyframepf.shape[0], emptyframepf.strides[0],QImage.Format.Format_RGB888)
imagep2f = QImage(emptyframep2f, emptyframep2f.shape[1],emptyframep2f.shape[0], emptyframep2f.strides[0],QImage.Format.Format_RGB888)
if self.showframescontinuously or self.nextframebool:
self.outputframe_1.setPixmap(QPixmap.fromImage(imagepf))
self.outputframe_5.setPixmap(QPixmap.fromImage(imagepf))
self.outputframe_3.setPixmap(QPixmap.fromImage(imagep2f))
self.currentframesaver(imagewithfilters) #Save latest frame in a variable
self.nextframebool = False
self.modify_startbutton("iniciar")
self.videoplaying = False
self.thread_stop_flag = False
self.start_stop_recording("stop")
def update_operatordisplay(self):
slot_count, apples = AppleIndexation.get_apple_data()
# Display apple count in QLCDNumber
self.Slot_LCD.display(slot_count)
# Parse apple list and count by types
big_apple_count = small_apple_count = bad_apple_count = false_positives = diameter_sum = 0
last_slot = -1
for slot_count, apple_type, diameter in apples:
if slot_count != last_slot:
if apple_type == "Grande":
big_apple_count += 1
diameter_sum += diameter
elif apple_type == "Pequena":
small_apple_count += 1
diameter_sum += diameter
elif apple_type == "Defeituosa":
bad_apple_count += 1
diameter_sum += diameter
slot_count += 1
else:
#keep only one detection per slot
false_positives += 1 #add the false positive
# Update QLCDNumber with counts
self.BigApples_LCD.display(big_apple_count)
self.SmallApples_LCD.display(small_apple_count)
self.BadApples_LCD.display(bad_apple_count)
total_apple_count = big_apple_count + small_apple_count + bad_apple_count
self.DetectedApples_LCD.display(big_apple_count+small_apple_count+bad_apple_count)
QMetaObject.invokeMethod(self.FalsePositives_TextEdit, "setHtml",
Qt.ConnectionType.QueuedConnection,
Q_ARG(str, "<div align='center'>{}</div>".format(false_positives)))
QMetaObject.invokeMethod(self.AverageDiameter_TextEdit, "setHtml",
Qt.ConnectionType.QueuedConnection,
Q_ARG(str, "<div align='center'>{}</div>".format(diameter_sum / total_apple_count if total_apple_count != 0 else 0.0)))
#Updates with LogFile
self.logFileReader.readLogFile()
def start_cameracapture(self):
import modules.LEDControl as LEDControl
self.nextframe_BT.setText("CONGELAR (C)")
self.nextframe_BT.setShortcut("C")
if self.videoplaying and self.showframescontinuously:
self.thread_stop_flag = True #STOP VIDEO PLAYBACK / CAMERA PLAYBACK
if self.camopen:
self.camopen = False
self.modify_startbutton("iniciar")
self.start_stop_recording("stop")
#LED Control
defaultbrightness = config.getint("IO_CONFIG", "light_default_intensity")
if config.getboolean("IO_CONFIG", "use_lights"):
try:
LEDControl.control_led_strip(MICROCONTROLLER_PORT, 0, 0, 0)
except:
self.show_error(f"Erro: Foi atingido o tempo limite de resposta do Microcontrolador\nVerifique se está conectado e o endereço da porta é o {MICROCONTROLLER_PORT}.")
else:
#LED Control
defaultbrightness = config.getint("IO_CONFIG", "light_default_intensity")
if config.getboolean("IO_CONFIG", "use_lights"):
try:
LEDControl.control_led_strip(MICROCONTROLLER_PORT, defaultbrightness, defaultbrightness, defaultbrightness)
except:
self.show_error(f"Erro: Foi atingido o tempo limite de resposta do Microcontrolador\nVerifique se está conectado e o endereço da porta é o {MICROCONTROLLER_PORT}.")
if not self.showframescontinuously:
self.showframescontinuously = True
self.start_BT.setText("PARAR (P)")
self.start_BT.setShortcut("P")
else:
self.progressBar.setValue(100) #RESET PROGRESSBAR
#Camera Test
# Try to access the default camera (usually the built-in webcam)
if USE_TWO_CAMERAS:
self.cap_left = cv2.VideoCapture(CAMERA_INDEX_LEFT)
self.cap_right = cv2.VideoCapture(CAMERA_INDEX_RIGHT)
# Check if the camera was opened successfully
if self.cap_left.isOpened() and self.cap_right.isOpened():
self.camopen = True
else:
self.camera = cv2.VideoCapture(0) # 0 represents the default camera
# Check if the camera was opened successfully
if self.camera.isOpened():
self.camopen = True
if self.camopen:
self.modify_startbutton("parar")
print("Processamento de Frames Iniciado")
threading.Thread(target=self.cameracapture_to_gui_thread).start() #Updates the gui with camera feed
def cameracapture_to_gui(self):
# Create a VideoCapture object
self.start_stop_recording("start")
with open(LOG_FILE_PATH, 'a') as log:
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log.write(f"{timestamp} - Processamento de câmara iniciado\n")
while not self.thread_stop_flag:
if USE_TWO_CAMERAS:
try:
self.camera = self.cap_left
ret_left, frame_left = self.cap_left.read()
ret_right, frame_right = self.cap_right.read()
except:
self.show_error("Erro: Câmara não disponível.")
#Preview the input filters
frame_left = FrameProcessor.ApplyInputFilters(frame_left, customdetectionfilter)
frame_right = FrameProcessor.ApplyInputFilters(frame_right, customdetectionfilter)
# Calculate the scale and apply resizing
self.hsv_left = cv2.cvtColor(frame_left, cv2.COLOR_BGR2HSV)
frame = frame_left = cv2.cvtColor(self.hsv_left, cv2.COLOR_HSV2RGB)
self.hsv_right = cv2.cvtColor(frame_right, cv2.COLOR_BGR2HSV)
frame_right = cv2.cvtColor(self.hsv_right, cv2.COLOR_HSV2RGB)
if not ret_left or not ret_right:
break
else:
try:
ret, frame = self.camera.read()
except:
self.show_warning("Erro: Câmara não disponível.")
#Preview the input filters
frame = FrameProcessor.ApplyInputFilters(frame, customdetectionfilter)
# Calculate the scale and apply resizing
self.hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
frame = cv2.cvtColor(self.hsv, cv2.COLOR_HSV2RGB)
if not ret:
break
self.videoplaying = True #bool to stop uploads while playing
#############################################################
width_scale = int(self.inputframe_1.width()) / frame.shape[1]
height_scale = int(self.inputframe_1.height()) / frame.shape[0]
scale = min(width_scale, height_scale)
frameoriginal = frame
frame = cv2.resize(frame, (int(frame.shape[1] * scale), int(frame.shape[0] * scale))) #small
#Calculate the scale and apply resizing 2
width_scale2 = int(self.inputframe_3.width()) / frameoriginal.shape[1]
height_scale2 = int(self.inputframe_3.height()) / frameoriginal.shape[0]
scale2 = min(width_scale2, height_scale2)
frame2 = cv2.resize(frameoriginal, (int(frameoriginal.shape[1] * scale2), int(frameoriginal.shape[0] * scale2))) #big
# Center the image
emptyframe = np.full((self.inputframe_1.height(), self.inputframe_1.width(), 3), (255, 255, 255), dtype=np.uint8)
x_offset = (self.inputframe_1.width() - frame.shape[1]) // 2
y_offset = (self.inputframe_1.height() - frame.shape[0]) // 2
# Center the image 2
emptyframe2 = np.full((self.inputframe_3.height(), self.inputframe_3.width(), 3), (255, 255, 255), dtype=np.uint8)
x_offset2 = (self.inputframe_3.width() - frame2.shape[1]) // 2
y_offset2 = (self.inputframe_3.height() - frame2.shape[0]) // 2
if USE_TWO_CAMERAS:
if self.detectionmode_COMBOBOX.currentIndex() in [-1, 0, 1, 2]:
# Resizing for inputframe2 and inputframe4
frameoriginal2 = frame_right
frame3 = cv2.resize(frameoriginal2, (int(frameoriginal2.shape[1] * scale), int(frameoriginal2.shape[0] * scale))) #small2
frame4 = cv2.resize(frameoriginal2, (int(frameoriginal2.shape[1] * scale2), int(frameoriginal2.shape[0] * scale2))) #big2
# Paste Frames in EmptyFrames
emptyframe3 = np.full((self.inputframe_2.height(), self.inputframe_2.width(), 3), (255, 255, 255), dtype=np.uint8)
emptyframe4 = np.full((self.inputframe_4.height(), self.inputframe_4.width(), 3), (255, 255, 255), dtype=np.uint8)
emptyframe[y_offset:y_offset + frame.shape[0], x_offset:x_offset + frame.shape[1]] = frame #small
emptyframe2[y_offset2:y_offset2 + frame2.shape[0], x_offset2:x_offset2 + frame2.shape[1]] = frame2 #big
emptyframe3[y_offset:y_offset + frame3.shape[0], x_offset:x_offset + frame3.shape[1]] = frame3 #small2
emptyframe4[y_offset2:y_offset2 + frame4.shape[0], x_offset2:x_offset2 + frame4.shape[1]] = frame4 #big2
# Convert image format
image = QImage(emptyframe, emptyframe.shape[1], emptyframe.shape[0], emptyframe.strides[0], QImage.Format.Format_RGB888)
image2 = QImage(emptyframe2, emptyframe2.shape[1], emptyframe2.shape[0], emptyframe2.strides[0], QImage.Format.Format_RGB888)
image3 = QImage(emptyframe3, emptyframe3.shape[1], emptyframe3.shape[0], emptyframe3.strides[0], QImage.Format.Format_RGB888)
image4 = QImage(emptyframe4, emptyframe4.shape[1], emptyframe4.shape[0], emptyframe4.strides[0], QImage.Format.Format_RGB888)
# Update the GUI
self.inputframe_1.setPixmap(QPixmap.fromImage(image))
self.inputframe_2.setPixmap(QPixmap.fromImage(image3))
self.inputframe_3.setPixmap(QPixmap.fromImage(image2))
self.inputframe_4.setPixmap(QPixmap.fromImage(image4))
# Frame processing
processor_result = FrameProcessor.CameraProcessor(frameoriginal, self.detectionmode_COMBOBOX.currentIndex(), self.categorizationmode_COMBOBOX.currentIndex(), self.threshold1_SLIDER.value(), self.threshold2_SLIDER.value(), filter, customdetectionfilter)
processor_result2 = FrameProcessor.CameraProcessor(frameoriginal2, self.detectionmode_COMBOBOX.currentIndex(), self.categorizationmode_COMBOBOX.currentIndex(), self.threshold1_SLIDER.value(), self.threshold2_SLIDER.value(), filter, customdetectionfilter)
if not processor_result[0] or not processor_result2[0]:
self.show_warning(processor_result[1])
else:
imagewithfilters = FrameProcessor.ApplyFilters(processor_result[1], filter)
imagewithfilters2 = FrameProcessor.ApplyFilters(processor_result2[1], filter)
# Ensure that processedvideoframe has the same dimensions as the target area
processedvideoframe = cv2.resize(imagewithfilters, (frame.shape[1], frame.shape[0]))
processedvideoframe2 = cv2.resize(imagewithfilters2, (frame.shape[1], frame.shape[0]))
processedvideoframe3 = cv2.resize(imagewithfilters, (frame2.shape[1], frame2.shape[0]))
processedvideoframe4 = cv2.resize(imagewithfilters2, (frame2.shape[1], frame2.shape[0]))
# Create an empty frame with the target dimensions
emptyframep = np.full((self.outputframe_1.height(), self.outputframe_1.width(), 3), (255, 255, 255), dtype=np.uint8)
emptyframep2 = np.full((self.outputframe_1.height(), self.outputframe_1.width(), 3), (255, 255, 255), dtype=np.uint8)
emptyframep3 = np.full((self.outputframe_3.height(), self.outputframe_3.width(), 3), (255, 255, 255), dtype=np.uint8)
emptyframep4 = np.full((self.outputframe_3.height(), self.outputframe_3.width(), 3), (255, 255, 255), dtype=np.uint8)
# Paste the resized frame onto the target area in emptyframep
emptyframep[y_offset:y_offset + frame.shape[0], x_offset:x_offset + frame.shape[1]] = processedvideoframe
emptyframep2[y_offset:y_offset + frame.shape[0], x_offset:x_offset + frame.shape[1]] = processedvideoframe2
emptyframep3[y_offset2:y_offset2 + frame2.shape[0], x_offset2:x_offset2 + frame2.shape[1]] = processedvideoframe3
emptyframep4[y_offset2:y_offset2 + frame2.shape[0], x_offset2:x_offset2 + frame2.shape[1]] = processedvideoframe4
# Convert image format
videoframep = QImage(emptyframep, emptyframep.shape[1], emptyframep.shape[0], emptyframep.strides[0], QImage.Format.Format_RGB888)
videoframep2 = QImage(emptyframep2, emptyframep2.shape[1], emptyframep2.shape[0], emptyframep2.strides[0], QImage.Format.Format_RGB888)
videoframep3 = QImage(emptyframep3, emptyframep3.shape[1], emptyframep3.shape[0], emptyframep3.strides[0], QImage.Format.Format_RGB888)
videoframep4 = QImage(emptyframep4, emptyframep4.shape[1], emptyframep4.shape[0], emptyframep4.strides[0], QImage.Format.Format_RGB888)
# Update the GUI
if self.showframescontinuously or self.nextframebool:
self.outputframe_1.setPixmap(QPixmap.fromImage(videoframep))
self.outputframe_5.setPixmap(QPixmap.fromImage(videoframep))
self.outputframe_3.setPixmap(QPixmap.fromImage(videoframep3))
self.outputframe_2.setPixmap(QPixmap.fromImage(videoframep2))
self.outputframe_6.setPixmap(QPixmap.fromImage(videoframep2))
self.outputframe_4.setPixmap(QPixmap.fromImage(videoframep4))
self.currentframesaver(processor_result[1]) #Save latest frame in a variable
self.currentframesaver2(processor_result2[1]) #Save latest frame in a variable
self.nextframebool = False
else:
calibframereturn = FrameProcessor.cameracalibrationprocessor(frameoriginal)
if calibframereturn != None:
inputframe = calibframereturn[1]
else:
inputframe = frameoriginal
imagewithfilters = FrameProcessor.ApplyFilters(inputframe, filter)
imagewithfilters2 = FrameProcessor.ApplyFilters(frameoriginal2, filter)
framepf = cv2.resize(imagewithfilters, (frame.shape[1], frame.shape[0]))
framep2f = cv2.resize(imagewithfilters, (frame2.shape[1], frame2.shape[0]))
framep3f = cv2.resize(imagewithfilters2, (frame.shape[1], frame.shape[0]))
framep4f = cv2.resize(imagewithfilters2, (frame2.shape[1], frame2.shape[0]))
emptyframepf = np.full((self.outputframe_1.height(), self.outputframe_1.width(), 3), (255, 255, 255), dtype=np.uint8) # Create an empty frame with the frame dimensions
emptyframepf[y_offset:y_offset+frame.shape[0], x_offset:x_offset+frame.shape[1]] = framepf # Paste the resized image onto the empty frame
emptyframep2f = np.full((self.outputframe_3.height(), self.outputframe_3.width(), 3), (255, 255, 255), dtype=np.uint8) # Create an empty frame with the frame dimensions
emptyframep2f[y_offset2:y_offset2+frame2.shape[0], x_offset2:x_offset2+frame2.shape[1]] = framep2f # Paste the resized image onto the empty frame
emptyframep3f = np.full((self.outputframe_1.height(), self.outputframe_1.width(), 3), (255, 255, 255), dtype=np.uint8) # Create an empty frame with the frame dimensions
emptyframep3f[y_offset:y_offset+frame.shape[0], x_offset:x_offset+frame.shape[1]] = framep3f # Paste the resized image onto the empty frame
emptyframep4f = np.full((self.outputframe_3.height(), self.outputframe_3.width(), 3), (255, 255, 255), dtype=np.uint8) # Create an empty frame with the frame dimensions
emptyframep4f[y_offset2:y_offset2+frame2.shape[0], x_offset2:x_offset2+frame2.shape[1]] = framep4f # Paste the resized image onto the empty frame
# Paste the resized image onto the empty frame
# ======================== UPDATE THE GUI ========================
videoframepf = QImage(emptyframepf, emptyframepf.shape[1], emptyframepf.shape[0], emptyframepf.strides[0], QImage.Format.Format_RGB888)
videoframep2f = QImage(emptyframep2f, emptyframep2f.shape[1], emptyframep2f.shape[0], emptyframep2f.strides[0], QImage.Format.Format_RGB888)
videoframep3f = QImage(emptyframep3f, emptyframepf.shape[1], emptyframepf.shape[0], emptyframepf.strides[0], QImage.Format.Format_RGB888)
videoframep4f = QImage(emptyframep4f, emptyframep2f.shape[1], emptyframep2f.shape[0], emptyframep2f.strides[0], QImage.Format.Format_RGB888)
if self.showframescontinuously or self.nextframebool:
self.outputframe_1.setPixmap(QPixmap.fromImage(videoframepf))
self.outputframe_5.setPixmap(QPixmap.fromImage(videoframepf))
self.outputframe_3.setPixmap(QPixmap.fromImage(videoframep3f))
self.outputframe_2.setPixmap(QPixmap.fromImage(videoframep2f))
self.outputframe_6.setPixmap(QPixmap.fromImage(videoframep2f))
self.outputframe_4.setPixmap(QPixmap.fromImage(videoframep4f))
self.currentframesaver(imagewithfilters) #Save latest frame in a variable
self.currentframesaver(imagewithfilters2) #Save latest frame in a variable
self.nextframebool = False
else:
emptyframe[y_offset:y_offset + frame.shape[0], x_offset:x_offset + frame.shape[1]] = frame
emptyframe2[y_offset2:y_offset2 + frame2.shape[0], x_offset2:x_offset2 + frame2.shape[1]] = frame2
image = QImage(emptyframe, emptyframe.shape[1], emptyframe.shape[0], emptyframe.strides[0], QImage.Format.Format_RGB888)
image2 = QImage(emptyframe2, emptyframe2.shape[1], emptyframe2.shape[0], emptyframe2.strides[0], QImage.Format.Format_RGB888)
self.inputframe_1.setPixmap(QPixmap.fromImage(image))
self.inputframe_3.setPixmap(QPixmap.fromImage(image2))
if self.detectionmode_COMBOBOX.currentIndex() in [-1, 0, 1, 2]:
processor_result = FrameProcessor.CameraProcessor(frameoriginal, self.detectionmode_COMBOBOX.currentIndex(), self.categorizationmode_COMBOBOX.currentIndex(), self.threshold1_SLIDER.value(), self.threshold2_SLIDER.value(), filter, customdetectionfilter)
if not processor_result[0]:
self.show_warning(processor_result[1])
else:
imagewithfilters = FrameProcessor.ApplyFilters(processor_result[1], filter)
# Ensure that processedvideoframe has the same dimensions as the target area
processedvideoframe = cv2.resize(imagewithfilters, (frame.shape[1], frame.shape[0]))
processedvideoframe2 = cv2.resize(imagewithfilters, (frame2.shape[1], frame2.shape[0]))
# Create an empty frame with the target dimensions
emptyframep = np.full((self.outputframe_1.height(), self.outputframe_1.width(), 3), (255, 255, 255), dtype=np.uint8)
emptyframep2 = np.full((self.outputframe_3.height(), self.outputframe_3.width(), 3), (255, 255, 255), dtype=np.uint8)
# Paste the resized frame onto the target area in emptyframep
emptyframep[y_offset:y_offset + frame.shape[0], x_offset:x_offset + frame.shape[1]] = processedvideoframe
emptyframep2[y_offset2:y_offset2 + frame2.shape[0], x_offset2:x_offset2 + frame2.shape[1]] = processedvideoframe2
# Convert image format
videoframep = QImage(emptyframep, emptyframep.shape[1], emptyframep.shape[0], emptyframep.strides[0], QImage.Format.Format_RGB888)
videoframep2 = QImage(emptyframep2, emptyframep2.shape[1], emptyframep2.shape[0], emptyframep2.strides[0], QImage.Format.Format_RGB888)
# Update the GUI
if self.showframescontinuously or self.nextframebool:
self.outputframe_1.setPixmap(QPixmap.fromImage(videoframep))
self.outputframe_5.setPixmap(QPixmap.fromImage(videoframep))
self.outputframe_3.setPixmap(QPixmap.fromImage(videoframep2))
self.currentframesaver(processor_result[1]) #Save latest frame in a variable
self.nextframebool = False
else:
calibframereturn = FrameProcessor.cameracalibrationprocessor(frameoriginal)
if calibframereturn != None:
inputframe = calibframereturn[1]
else:
inputframe = frameoriginal
# Update the GUI
imagewithfilters = FrameProcessor.ApplyFilters(inputframe, filter)
framepf = cv2.resize(imagewithfilters, (frame.shape[1], frame.shape[0]))
framep2f = cv2.resize(imagewithfilters, (frame2.shape[1], frame2.shape[0]))
emptyframepf = np.full((self.outputframe_1.height(), self.outputframe_1.width(), 3), (255, 255, 255), dtype=np.uint8) # Create an empty frame with the frame dimensions
emptyframepf[y_offset:y_offset+frame.shape[0], x_offset:x_offset+frame.shape[1]] = framepf # Paste the resized image onto the empty frame
emptyframep2f = np.full((self.outputframe_3.height(), self.outputframe_3.width(), 3), (255, 255, 255), dtype=np.uint8) # Create an empty frame with the frame dimensions
emptyframep2f[y_offset2:y_offset2+frame2.shape[0], x_offset2:x_offset2+frame2.shape[1]] = framep2f # Paste the resized image onto the empty frame
# Paste the resized image onto the empty frame
# ======================== UPDATE THE GUI ========================
imagepf = QImage(emptyframepf, emptyframepf.shape[1],emptyframepf.shape[0], emptyframepf.strides[0],QImage.Format.Format_RGB888)
imagep2f = QImage(emptyframep2f, emptyframep2f.shape[1],emptyframep2f.shape[0], emptyframep2f.strides[0],QImage.Format.Format_RGB888)
if self.showframescontinuously or self.nextframebool:
self.outputframe_1.setPixmap(QPixmap.fromImage(imagepf))
self.outputframe_5.setPixmap(QPixmap.fromImage(imagepf))
self.outputframe_3.setPixmap(QPixmap.fromImage(imagep2f))
self.currentframesaver(imagewithfilters) #Save latest frame in a variable
self.nextframebool = False
#Update OPERATOR UI
self.update_operatordisplay()
self.modify_startbutton("iniciar")
self.videoplaying = False
videoplaying = False
self.thread_stop_flag = False
# Release the camera when you're done
if USE_TWO_CAMERAS:
self.cap_left.release()
self.cap_right.release()
else:
self.camera.release()
self.start_stop_recording("stop")
def currentframesaver(self, frame):
height, width, channel = frame.shape
bytes_per_line = 3 * width
q_image = QImage(frame.data, width, height, bytes_per_line, QImage.Format.Format_RGB888)
pixmap = QPixmap.fromImage(q_image)
self.currentimageframe = pixmap
global currentimageframe
currentimageframe = pixmap
def currentframesaver2(self, frame):
height, width, channel = frame.shape
bytes_per_line = 3 * width
q_image = QImage(frame.data, width, height, bytes_per_line, QImage.Format.Format_RGB888)
pixmap = QPixmap.fromImage(q_image)
self.currentimageframe2 = pixmap
global currentimageframe2
currentimageframe2 = pixmap
def small_vw(self):
self.stackedWidget.setCurrentIndex(0)
self.resize(771, 586)
def big_vw(self):
self.stackedWidget.setCurrentIndex(1)
self.resize(771, 586)
def operator_vw(self):
self.stackedWidget.setCurrentIndex(2)
self.resize(771, 586)
def resetapplecount(self):
AppleIndexation.reset_apple_list()
def save_frame(self):
if currentimageframe != None:
# Get pixel data from the QPixmap
savefile_dialog_path, _ = QFileDialog.getSaveFileName(self, "Guardar", "", "Ficheiros de Imagem (*.jpg *.jpeg *.png *.bmp *.tiff *.tif *.gif *.pbm *.pgm *.ppm *.xbm *.xpm *.sr *.webp);;All Files (*)")
if savefile_dialog_path:
pixmap = currentimageframe
if not pixmap.isNull():
try:
pixmap.save(savefile_dialog_path)
self.show_info(f"Imagem Guardada: {savefile_dialog_path}")
except Exception as e:
self.show_error(f"Erro ao Guardar a Imagem: {str(e)}")
else:
self.show_error(f"Erro: Não pode gravar uma imagem em branco.")
if USE_TWO_CAMERAS:
savefile_dialog_path2, _ = QFileDialog.getSaveFileName(self, "Guardar 2º", "", "Ficheiros de Imagem (*.jpg *.jpeg *.png *.bmp *.tiff *.tif *.gif *.pbm *.pgm *.ppm *.xbm *.xpm *.sr *.webp);;All Files (*)")
if savefile_dialog_path2:
pixmap2 = currentimageframe2
if not pixmap2.isNull():
try:
pixmap2.save(savefile_dialog_path2)
self.show_info(f"Imagem 2 Guardada: {savefile_dialog_path2}")
except Exception as e:
self.show_error(f"Erro ao Guardar a 2ª Imagem: {str(e)}")
else:
self.show_error(f"Erro: Não pode gravar uma imagem em branco.")
else:
self.show_warning("Erro: Comece uma captura de câmara ou abra um ficheiro.")
def save_file(self):
if not self.videoplaying and not self.camopen:
self.save_frame()
else:
self.save_video()
def save_video(self):
if self.video_writer is not None:
self.video_writer.release()
# Open a file dialog to choose save location and format
file_dialog = QFileDialog(self)
file_dialog.setWindowTitle("Guardar Vídeo")
file_dialog.setAcceptMode(QFileDialog.AcceptMode.AcceptSave)
file_dialog.setFileMode(QFileDialog.FileMode.AnyFile)
file_dialog.setNameFilter("Ficheiros de Vídeo (*.avi *.mp4 *.mkv *.mov);;Todos os Ficheiros (*)")
if file_dialog.exec() == QFileDialog.DialogCode.Accepted and self.video_writer != None:
save_path = file_dialog.selectedFiles()[0]
_, file_extension = os.path.splitext(save_path)
fourcc = cv2.VideoWriter_fourcc(*'XVID') # Default to AVI format
if file_extension.lower() == '.mp4':
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
elif file_extension.lower() == '.mkv':
fourcc = cv2.VideoWriter_fourcc(*'X264')
elif file_extension.lower() == '.mov':
fourcc = cv2.VideoWriter_fourcc(*'X264')
# Change the codec of the existing VideoWriter
self.video_writer.set(cv2.CAP_PROP_FOURCC, fourcc)
if os.path.exists(self.temp_filename):
if os.path.exists(save_path):
os.remove(save_path)
os.rename(self.temp_filename, save_path)
self.show_info(f"Video Guardado: {save_path}")
else:
self.show_error(f"Erro de Gravação: Ficheiro Temporário '{self.temp_filename}' não encontrado.")
if os.path.exists(self.temp_filename):
os.remove(self.temp_filename)
elif self.video_writer == None:
self.show_warning("Erro: Comece uma captura de câmara ou abra um ficheiro.")
if USE_TWO_CAMERAS:
# Open a file dialog to choose save location and format
file_dialog2 = QFileDialog(self)
file_dialog2.setWindowTitle("Guardar Vídeo 2")
file_dialog2.setAcceptMode(QFileDialog.AcceptMode.AcceptSave)
file_dialog2.setFileMode(QFileDialog.FileMode.AnyFile)
file_dialog2.setNameFilter("Ficheiros de Vídeo (*.avi *.mp4 *.mkv *.mov);;Todos os Ficheiros (*)")
if file_dialog2.exec() == QFileDialog.DialogCode.Accepted and self.video_writer2 != None:
save_path2 = file_dialog2.selectedFiles()[0]
_, file_extension = os.path.splitext(save_path2)
fourcc = cv2.VideoWriter_fourcc(*'XVID') # Default to AVI format
if file_extension.lower() == '.mp4':
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
elif file_extension.lower() == '.mkv':
fourcc = cv2.VideoWriter_fourcc(*'X264')
elif file_extension.lower() == '.mov':
fourcc = cv2.VideoWriter_fourcc(*'X264')
# Change the codec of the existing VideoWriter
self.video_writer2.set(cv2.CAP_PROP_FOURCC, fourcc)
if os.path.exists(self.temp_filename2):
if os.path.exists(save_path2):
os.remove(save_path2)
os.rename(self.temp_filename2, save_path2)
self.show_info(f"Video Guardado: {save_path2}")
else:
self.show_error(f"Erro de Gravação: Ficheiro Temporário '{self.temp_filename2}' não encontrado.")
if os.path.exists(self.temp_filename2):
os.remove(self.temp_filename2)
elif self.video_writer2 == None:
self.show_warning("Erro: Comece uma captura de câmara ou abra um ficheiro.")
self.start_stop_recording("reload")
def frame_record(self):
frame_interval = 1 / self.framerate # Calculate the desired frame interval
while not self.stop_recording_tag:
start_time = time.time()
if currentimageframe is not None:
frame = currentimageframe.toImage().convertToFormat(QImage.Format.Format_RGB888)
frame = frame.scaled(self.resolution[0],self.resolution[1])
ptr = frame.bits()
ptr.setsize(frame.sizeInBytes())
frame = np.array(ptr).reshape(frame.height(), frame.width(), 3)
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
if self.last_frame_time is not None:
time_elapsed = time.time() - self.last_frame_time
if time_elapsed < frame_interval:
sleep_time = frame_interval - time_elapsed
time.sleep(sleep_time)
self.video_writer.write(frame)
self.last_frame_time = time.time()
self.frame_index += 1
if USE_TWO_CAMERAS and currentimageframe2 is not None:
frame2 = currentimageframe2.toImage().convertToFormat(QImage.Format.Format_RGB888)
frame2 = frame2.scaled(self.resolution[0],self.resolution[1])
ptr2 = frame2.bits()
ptr2.setsize(frame2.sizeInBytes())
frame2 = np.array(ptr2).reshape(frame2.height(), frame2.width(), 3)
frame2 = cv2.cvtColor(frame2, cv2.COLOR_RGB2BGR)
if self.last_frame_time is not None:
time_elapsed = time.time() - self.last_frame_time
if time_elapsed < frame_interval:
sleep_time = frame_interval - time_elapsed
time.sleep(sleep_time)
self.video_writer2.write(frame2)
end_time = time.time()
elapsed_time = end_time - start_time
if elapsed_time < frame_interval:
sleep_time = frame_interval - elapsed_time
time.sleep(sleep_time)
def start_stop_recording(self, state):
self.framerate = 60 #fps
self.resolution = (1440, 1080)
if state == "start":
self.frame_index = 0
self.stop_recording_tag = False # Reset the stop_recording_tag
# Create a temporary video file
temp_dir = tempfile.gettempdir()
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
#self.temp_filename = os.path.join(temp_dir, f"temp_video_{timestamp}.avi")
self.temp_filename = os.path.join(temp_dir, f"temp_video.avi")
self.temp_filename2 = os.path.join(temp_dir, f"temp_video2.avi")
self.fourcc = cv2.VideoWriter_fourcc(*'XVID')
self.video_writer = cv2.VideoWriter(self.temp_filename, self.fourcc, self.framerate, self.resolution)
if USE_TWO_CAMERAS:
self.video_writer2 = cv2.VideoWriter(self.temp_filename2, self.fourcc, self.framerate, self.resolution)
self.last_frame_time = time.time()
threading.Thread(target=self.recording_thread).start() # Start frame recording
elif state == "reload":
self.frame_index = 0
self.stop_recording_tag = False # Reset the stop_recording_tag
# Create a temporary video file
temp_dir = tempfile.gettempdir()
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
#self.temp_filename = os.path.join(temp_dir, f"temp_video_{timestamp}.avi")
self.temp_filename = os.path.join(temp_dir, "temp_video.avi")
self.temp_filename2 = os.path.join(temp_dir, "temp_video2.avi")
self.fourcc = cv2.VideoWriter_fourcc(*'XVID')
self.video_writer.open(self.temp_filename, self.fourcc, self.framerate, self.resolution)
if USE_TWO_CAMERAS:
self.video_writer2.open(self.temp_filename2, self.fourcc, self.framerate, self.resolution)
else:
self.stop_recording_tag = True
def logs_save(self):
savefile_dialog_path, _ = QFileDialog.getSaveFileName(self, "Guardar Ficheiro de Logs", "", "Ficheiro de Texto (*.txt);;Todos os Ficheiros (*)")
if savefile_dialog_path:
# Copy logs file to the chosen path
source_file = config.get('LOGS_CONFIG', 'LOGS_FILE_PATH')
with open(source_file, "rb") as src_file, open(savefile_dialog_path, "wb") as dest_file:
dest_file.write(src_file.read())
def logs_open(self):
file_path = config.get('LOGS_CONFIG', 'LOGS_FILE_PATH')
if sys.platform.startswith('win'):
os.startfile(file_path)
elif sys.platform.startswith('darwin'):
subprocess.run(['open', file_path])
elif sys.platform.startswith('linux'):
subprocess.run(['xdg-open', file_path])
else:
self.show_error("Erro: OS não suportado.")
def settings_open(self):
config_path = "config.ini"
if sys.platform.startswith('win'):
os.startfile(config_path)
elif sys.platform.startswith('darwin'):
subprocess.run(['open', config_path])
elif sys.platform.startswith('linux'):
subprocess.run(['xdg-open', config_path])
else:
self.show_error("Erro: OS não suportado.")
def colorfilters_open(self):
os.chdir(os.path.dirname(os.path.abspath(__file__)))
try:
self.colorfilters = ColorFilters()
self.colorfilters.show()
self.inputfilters = InputFilters()
self.inputfilters.show()
except UILoadingException as exp:
MyApp.show_error(self, str(exp))
def info_open(self):
info_dialog = AboutDialog()
info_dialog.exec()
def detectionmode_changed(self):
'''
try:
self.inputfilters = InputFilters()
self.inputfilters.close() #close filters if opened-
except:
pass