-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.py
More file actions
1137 lines (900 loc) · 34.7 KB
/
Copy pathtest.py
File metadata and controls
1137 lines (900 loc) · 34.7 KB
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
# -*- coding: utf-8 -*-
import sys
import cv2
import numpy as np
import threading
import os
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QMessageBox, QWidget,QSizePolicy,
QVBoxLayout, QHBoxLayout, QLabel, QDockWidget
)
from PyQt5.QtCore import QTimer, Qt
from PyQt5.QtGui import QImage, QPixmap, QColor, QPalette, QFont
from CamOperation_class import CameraOperation
from MvCameraControl_class import *
from MvErrorDefine_const import *
from CameraParams_header import *
from PyUICBasicDemo import Ui_MainWindow,apply_styles
import ctypes
import glob
from datetime import datetime
# Toggle: whether debug saves are enabled
global is_debug_save_enabled
is_debug_save_enabled = False
global detected_holes_memory
detected_holes_memory = []
# def detect_holes(image):
# global detected_holes_memory
# output = image.copy()
# H, W = image.shape[:2]
# # =====================================================
# # FIXED CENTER WINDOW
# # =====================================================
# ROI_W = 900
# ROI_H = 700
# roi_x1 = (W - ROI_W) // 2
# roi_y1 = (H - ROI_H) // 2
# roi_x2 = roi_x1 + ROI_W
# roi_y2 = roi_y1 + ROI_H
# # Draw ROI window
# cv2.rectangle(
# output,
# (roi_x1, roi_y1),
# (roi_x2, roi_y2),
# (0, 255, 255),
# 2
# )
# # =====================================================
# # PROCESS ONLY ROI
# # =====================================================
# roi = image[roi_y1:roi_y2, roi_x1:roi_x2]
# gray = cv2.cvtColor(
# roi,
# cv2.COLOR_BGR2GRAY
# )
# blur = cv2.GaussianBlur(
# gray,
# (9, 9),
# 2
# )
# # =====================================================
# # HOUGH CIRCLE DETECTION
# # =====================================================
# circles = cv2.HoughCircles(
# blur,
# cv2.HOUGH_GRADIENT,
# dp=1.1,
# minDist=35,
# param1=120,
# param2=18,
# minRadius=5,
# maxRadius=35
# )
# # =====================================================
# # THRESHOLD VISUALIZATION
# # =====================================================
# thresh_vis = cv2.cvtColor(
# blur,
# cv2.COLOR_GRAY2BGR
# )
# # =====================================================
# # TOTAL COUNT
# # =====================================================
# hole_count = len(detected_holes_memory)
# # =====================================================
# # NO CIRCLES FOUND
# # =====================================================
# if circles is None:
# cv2.putText(
# output,
# f"TOTAL: {hole_count}",
# (40, 90),
# cv2.FONT_HERSHEY_SIMPLEX,
# 2.2,
# (0, 255, 255),
# 5
# )
# return hole_count, output, thresh_vis
# # =====================================================
# # PROCESS DETECTED CIRCLES
# # =====================================================
# circles = np.round(circles[0, :]).astype(int)
# for (x, y, r) in circles:
# # ROI -> FULL IMAGE COORDS
# gx = x + roi_x1
# gy = y + roi_y1
# # =====================================================
# # CHECK MEMORY
# # =====================================================
# is_new_hole = True
# for px, py in detected_holes_memory:
# distance = np.sqrt(
# (gx - px) ** 2 +
# (gy - py) ** 2
# )
# # Already counted
# if distance < 40:
# is_new_hole = False
# break
# # =====================================================
# # NEW HOLE
# # =====================================================
# if is_new_hole:
# detected_holes_memory.append((gx, gy))
# hole_count += 1
# color = (0, 255, 0)
# # =====================================================
# # OLD HOLE
# # =====================================================
# else:
# color = (255, 0, 0)
# # =====================================================
# # DRAW DETECTION
# # =====================================================
# cv2.circle(
# output,
# (gx, gy),
# r,
# color,
# 2
# )
# # Center point
# cv2.circle(
# output,
# (gx, gy),
# 3,
# (0, 0, 255),
# -1
# )
# # Label
# cv2.putText(
# output,
# str(hole_count),
# (gx - 10, gy - r - 10),
# cv2.FONT_HERSHEY_SIMPLEX,
# 0.6,
# color,
# 2
# )
# # =====================================================
# # TOTAL TEXT
# # =====================================================
# cv2.putText(
# output,
# f"TOTAL: {hole_count}",
# (40, 90),
# cv2.FONT_HERSHEY_SIMPLEX,
# 2.2,
# (0, 255, 255),
# 5
# )
# return hole_count, output, thresh_vis
# ---------------------------------------------------
# MAIN METHOD
# ---------------------------------------------------
def detect_holes(image):
output = image.copy()
H, W = image.shape[:2]
# =====================================================
# FIXED CENTER WINDOW
# =====================================================
ROI_W = 900
ROI_H = 700
x1 = (W - ROI_W) // 2
y1 = (H - ROI_H) // 2
x2 = x1 + ROI_W
y2 = y1 + ROI_H
# Draw ROI window
cv2.rectangle(
output,
(x1, y1),
(x2, y2),
(0, 255, 255),
2
)
# =====================================================
# PROCESS ONLY ROI
# =====================================================
roi = image[y1:y2, x1:x2]
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
_, thresh = cv2.threshold(
blur,
80,
255,
cv2.THRESH_BINARY_INV
)
kernel = np.ones((3, 3), np.uint8)
thresh = cv2.morphologyEx(
thresh,
cv2.MORPH_OPEN,
kernel
)
contours, _ = cv2.findContours(
thresh,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE
)
hole_count = len(detected_holes_memory)
for cnt in contours:
area = cv2.contourArea(cnt)
if area < 100:
continue
perimeter = cv2.arcLength(cnt, True)
if perimeter == 0:
continue
circularity = (
4 * np.pi * area /
(perimeter * perimeter)
)
if circularity < 0.7:
continue
x, y, w, h = cv2.boundingRect(cnt)
aspect_ratio = w / float(h)
if aspect_ratio < 0.75 or aspect_ratio > 1.25:
continue
# ROI coords
cx = x + w // 2
cy = y + h // 2
# Full image coords
gx = cx + x1
gy = cy + y1
radius = max(w, h) // 2
# =====================================================
# CHECK MEMORY
# =====================================================
is_new_hole = True
for px, py in detected_holes_memory:
distance = np.sqrt(
(gx - px) ** 2 +
(gy - py) ** 2
)
if distance < 40:
is_new_hole = False
break
# =====================================================
# NEW HOLE
# =====================================================
if is_new_hole:
detected_holes_memory.append((gx, gy))
hole_count += 1
color = (0, 255, 0)
else:
color = (255, 0, 0)
# =====================================================
# DRAW
# =====================================================
cv2.circle(
output,
(gx, gy),
radius,
color,
2
)
cv2.circle(
output,
(gx, gy),
3,
(0, 0, 255),
-1
)
cv2.putText(
output,
str(hole_count),
(gx - 10, gy - radius - 10),
cv2.FONT_HERSHEY_SIMPLEX,
0.6,
color,
2
)
# is_new_hole = True
# for px, py in detected_holes_memory:
# distance = np.sqrt(
# (gx - px) ** 2 +
# (gy - py) ** 2
# )
# # Same hole already counted
# if distance < 40:
# is_new_hole = False
# break
# ------------------------------------------------
# COUNT ONLY NEW HOLES
# ------------------------------------------------
# if is_new_hole:
# detected_holes_memory.append((gx, gy))
# hole_count += 1
# Draw GREEN = new counted hole
# cv2.circle(
# output,
# (gx, gy),
# radius,
# (0, 255, 0),
# 2
# )
# cv2.putText(
# output,
# str(hole_count),
# (gx - 10, gy - radius - 10),
# cv2.FONT_HERSHEY_SIMPLEX,
# 0.6,
# (0, 255, 0),
# 2
# )
# else:
# # Already counted hole
# # Draw BLUE
# cv2.circle(
# output,
# (gx, gy),
# radius,
# (255, 0, 0),
# 2
# )
# =====================================================
# TOTAL COUNT
# =====================================================
cv2.putText(
output,
f"TOTAL: {hole_count}",
(40, 90),
cv2.FONT_HERSHEY_SIMPLEX,
2.2,
(0, 255, 255),
5
)
# =====================================================
# THRESH VIS
# =====================================================
thresh_vis = cv2.cvtColor(
thresh,
cv2.COLOR_GRAY2BGR
)
return hole_count, output, thresh_vis
# ─────────────────────────────────────────────
# Frame Processor: runs in a background thread
# ─────────────────────────────────────────────
class GoNoGoProcessor:
"""
Continuously grabs the latest frame from the camera using GetImageBuffer,
runs GO/NO-GO detection, and emits results via a callback.
"""
def __init__(self, cam_operation_ref, result_callback):
self.cam_op = cam_operation_ref
self.callback = result_callback
self._running = False
self._thread = None
def start(self):
self._running = True
self._thread = threading.Thread(target=self._loop, daemon=True)
self._thread.start()
def stop(self):
self._running = False
def _loop(self):
stOutFrame = MV_FRAME_OUT()
ctypes.memset(ctypes.byref(stOutFrame), 0, ctypes.sizeof(stOutFrame))
while self._running:
ret = self.cam_op.obj_cam.MV_CC_GetImageBuffer(stOutFrame, 1000)
if ret != MV_OK:
continue
try:
img = self._frame_to_bgr(stOutFrame)
if img is not None:
hole_count, result_img, thresh_img = detect_holes(img)
self.callback(
f"COUNT: {hole_count}",
hole_count,
result_img,
thresh_img
)
finally:
self.cam_op.obj_cam.MV_CC_FreeImageBuffer(stOutFrame)
def _frame_to_bgr(self, frame):
"""Convert MV_FRAME_OUT to a BGR numpy array."""
try:
pixel_fmt = frame.stFrameInfo.enPixelType
w = frame.stFrameInfo.nWidth
h = frame.stFrameInfo.nHeight
buf_size = frame.stFrameInfo.nFrameLen
raw = (ctypes.c_ubyte * buf_size)()
ctypes.memmove(raw, frame.pBufAddr, buf_size)
arr = np.frombuffer(raw, dtype=np.uint8)
# Common pixel format handling
if pixel_fmt == PixelType_Gvsp_Mono8:
img = arr.reshape((h, w))
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
elif pixel_fmt in (PixelType_Gvsp_RGB8_Packed,):
img = arr.reshape((h, w, 3))
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
elif pixel_fmt in (PixelType_Gvsp_BayerRG8, PixelType_Gvsp_BayerGR8,
PixelType_Gvsp_BayerBG8, PixelType_Gvsp_BayerGB8):
img = arr.reshape((h, w))
bayer_map = {
PixelType_Gvsp_BayerRG8: cv2.COLOR_BayerRG2BGR,
PixelType_Gvsp_BayerGR8: cv2.COLOR_BayerGR2BGR,
PixelType_Gvsp_BayerBG8: cv2.COLOR_BayerBG2BGR,
PixelType_Gvsp_BayerGB8: cv2.COLOR_BayerGB2BGR,
}
img = cv2.cvtColor(img, bayer_map[pixel_fmt])
else:
# Fallback: try treating as mono
img = arr.reshape((h, w)) if arr.size == h * w else None
return img
except Exception as e:
print(f"[GoNoGoProcessor] Frame conversion error: {e}")
return None
# ─────────────────────────────────────────────
# Helper utilities (unchanged from original)
# ─────────────────────────────────────────────
def TxtWrapBy(start_str, end, all):
start = all.find(start_str)
if start >= 0:
start += len(start_str)
end = all.find(end, start)
if end >= 0:
return all[start:end].strip()
def ToHexStr(num):
chaDic = {10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f'}
hexStr = ""
if num < 0:
num = num + 2 ** 32
while num >= 16:
digit = num % 16
hexStr = chaDic.get(digit, str(digit)) + hexStr
num //= 16
hexStr = chaDic.get(num, str(num)) + hexStr
return hexStr
def decoding_char(ctypes_char_array):
byte_str = memoryview(ctypes_char_array).tobytes()
null_index = byte_str.find(b'\x00')
if null_index != -1:
byte_str = byte_str[:null_index]
for encoding in ['gbk', 'utf-8', 'latin-1']:
try:
return byte_str.decode(encoding)
except UnicodeDecodeError:
continue
return byte_str.decode('latin-1', errors='replace')
# ─────────────────────────────────────────────
# Result Overlay Widget
# ─────────────────────────────────────────────
class GoNoGoOverlay(QWidget):
"""
A floating overlay panel that shows the live GO/NO-GO result,
edge score, and a small preview of the detected crop + masked edges.
Attach it next to the camera display widget.
"""
def __init__(self, parent=None):
super().__init__(parent)
# self.setFixedWidth(320)
self.setSizePolicy(
QSizePolicy.Expanding, QSizePolicy.Expanding
)
self._build_ui()
def _build_ui(self):
layout = QVBoxLayout(self)
layout.setContentsMargins(10, 10, 10, 10)
layout.setSpacing(8)
# ── Result badge ──
self.lbl_result = QLabel("WAITING")
self.lbl_result.setAlignment(Qt.AlignCenter)
self.lbl_result.setFixedHeight(64)
font = QFont("Courier New", 22, QFont.Bold)
self.lbl_result.setFont(font)
self.lbl_result.setStyleSheet("""
QLabel {
background: #2a2a2a;
color: #aaaaaa;
border-radius: 8px;
letter-spacing: 3px;
}
""")
layout.addWidget(self.lbl_result)
# ── Score ──
self.lbl_score = QLabel("Count: —")
self.lbl_score.setAlignment(Qt.AlignCenter)
self.lbl_score.setFont(QFont("Courier New", 11))
self.lbl_score.setStyleSheet("color: #cccccc;")
layout.addWidget(self.lbl_score)
# ── Crop preview row ──
preview_row = QHBoxLayout()
self.lbl_crop_title = QLabel("Hole detection")
self.lbl_crop_title.setAlignment(Qt.AlignCenter)
self.lbl_crop_title.setFont(QFont("Courier New", 9))
self.lbl_crop_title.setStyleSheet("color: #888;")
self.lbl_edges_title = QLabel("Threshold / Debug")
self.lbl_edges_title.setAlignment(Qt.AlignCenter)
self.lbl_edges_title.setFont(QFont("Courier New", 9))
self.lbl_edges_title.setStyleSheet("color: #888;")
col1 = QVBoxLayout()
col1.addWidget(self.lbl_crop_title)
self.lbl_crop = QLabel()
self.lbl_crop.setFixedSize(140, 140)
self.lbl_crop.setAlignment(Qt.AlignCenter)
self.lbl_crop.setStyleSheet("background: #1a1a1a; border-radius: 4px;")
col1.addWidget(self.lbl_crop)
col2 = QVBoxLayout()
col2.addWidget(self.lbl_edges_title)
self.lbl_edges = QLabel()
self.lbl_edges.setFixedSize(140, 140)
self.lbl_edges.setAlignment(Qt.AlignCenter)
self.lbl_edges.setStyleSheet("background: #1a1a1a; border-radius: 4px;")
col2.addWidget(self.lbl_edges)
preview_row.addLayout(col1)
preview_row.addLayout(col2)
layout.addLayout(preview_row)
# ── Threshold note ──
self.lbl_threshold = QLabel("Threshold: score > 1200 → NO-GO")
self.lbl_threshold.setAlignment(Qt.AlignCenter)
self.lbl_threshold.setFont(QFont("Courier New", 9))
self.lbl_threshold.setStyleSheet("color: #555;")
layout.addWidget(self.lbl_threshold)
layout.addStretch()
def update_result(self, result, score, crop_img, masked_img):
"""Call this from the main thread via QTimer/signal to update UI."""
if "COUNT" in result:
color = "#00cc66"
bg = "#0a2e1a"
elif result == "DETECTING...":
color = "#ffaa00"
bg = "#3a2a00"
elif result == "NO HOLES":
color = "#ff3333"
bg = "#2e0a0a"
else:
color = "#aaaaaa"
bg = "#2a2a2a"
self.lbl_result.setText(result)
self.lbl_result.setStyleSheet(f"""
QLabel {{
background: {bg};
color: {color};
border-radius: 8px;
letter-spacing: 3px;
border: 2px solid {color};
}}
""")
self.lbl_score.setText(f"Edge Score: {score}")
if crop_img is not None:
self._set_label_image(self.lbl_crop, crop_img)
else:
self.lbl_crop.clear()
self.lbl_crop.setText("No button\ndetected")
self.lbl_crop.setStyleSheet("background: #1a1a1a; color: #555; border-radius: 4px;")
if masked_img is not None:
self._set_label_image(self.lbl_edges, masked_img)
else:
self.lbl_edges.clear()
def _set_label_image(self, label, bgr_img):
"""Convert a BGR numpy array to QPixmap and display in a QLabel."""
rgb = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2RGB)
h, w, ch = rgb.shape
qimg = QImage(rgb.data, w, h, ch * w, QImage.Format_RGB888)
pix = QPixmap.fromImage(qimg).scaled(
label.width(), label.height(),
Qt.KeepAspectRatio, Qt.SmoothTransformation
)
label.setPixmap(pix)
# ─────────────────────────────────────────────
# Main Application
# ─────────────────────────────────────────────
if __name__ == "__main__":
MvCamera.MV_CC_Initialize()
global deviceList
deviceList = MV_CC_DEVICE_INFO_LIST()
global cam
cam = MvCamera()
global nSelCamIndex
nSelCamIndex = 0
global obj_cam_operation
obj_cam_operation = 0
global isOpen
isOpen = False
global isGrabbing
isGrabbing = False
global isCalibMode
isCalibMode = True
# GO/NOGO processor instance (created on start_grabbing)
global gonogo_processor
gonogo_processor = None
# ── Latest result cache (written by bg thread, read by QTimer on main thread) ──
_latest_result = {"result": None, "score": 0, "crop": None, "masked": None}
_result_lock = threading.Lock()
def _on_gonogo_result(result, score, crop, masked):
"""Called from background thread — just cache, don't touch Qt here."""
with _result_lock:
_latest_result["result"] = result
_latest_result["score"] = score
_latest_result["crop"] = crop.copy() if crop is not None else None
_latest_result["masked"] = masked.copy() if masked is not None else None
# QTimer polls the cache and pushes to UI safely on the main thread
ui_refresh_timer = QTimer()
def _refresh_ui():
with _result_lock:
r = _latest_result["result"]
s = _latest_result["score"]
c = _latest_result["crop"]
m = _latest_result["masked"]
if r is not None:
overlay_widget.update_result(r, s, c, m)
if c is not None:
show_main_image(c)
ui_refresh_timer.timeout.connect(_refresh_ui)
def show_main_image(img):
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
h, w, ch = rgb.shape
qimg = QImage(
rgb.data,
w,
h,
ch * w,
QImage.Format_RGB888
)
pix = QPixmap.fromImage(qimg)
pix = pix.scaled(
ui.widgetDisplay.width(),
ui.widgetDisplay.height(),
Qt.KeepAspectRatio,
Qt.SmoothTransformation
)
ui.widgetDisplay.setPixmap(pix)
# ── Camera UI callbacks (all unchanged, except start/stop_grabbing) ──
def enum_devices():
global deviceList, obj_cam_operation
deviceList = MV_CC_DEVICE_INFO_LIST()
n_layer_type = (MV_GIGE_DEVICE | MV_USB_DEVICE | MV_GENTL_CAMERALINK_DEVICE
| MV_GENTL_CXP_DEVICE | MV_GENTL_XOF_DEVICE)
ret = MvCamera.MV_CC_EnumDevices(n_layer_type, deviceList)
if ret != 0:
QMessageBox.warning(mainWindow, "Error", "Enum devices fail! ret = :" + ToHexStr(ret), QMessageBox.Ok)
return ret
if deviceList.nDeviceNum == 0:
QMessageBox.warning(mainWindow, "Info", "Find no device", QMessageBox.Ok)
return ret
print("Find %d devices!" % deviceList.nDeviceNum)
devList = []
for i in range(0, deviceList.nDeviceNum):
mvcc_dev_info = cast(deviceList.pDeviceInfo[i], POINTER(MV_CC_DEVICE_INFO)).contents
if mvcc_dev_info.nTLayerType in (MV_GIGE_DEVICE, MV_GENTL_GIGE_DEVICE):
info = mvcc_dev_info.SpecialInfo.stGigEInfo
name = decoding_char(info.chUserDefinedName)
model = decoding_char(info.chModelName)
ip = info.nCurrentIp
nip = ((ip >> 24) & 0xff, (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff)
devList.append(f"[{i}]GigE: {name} {model}({'.'.join(map(str,nip))})")
elif mvcc_dev_info.nTLayerType == MV_USB_DEVICE:
info = mvcc_dev_info.SpecialInfo.stUsb3VInfo
name = decoding_char(info.chUserDefinedName)
model = decoding_char(info.chModelName)
sn = "".join(chr(c) for c in info.chSerialNumber if c != 0)
devList.append(f"[{i}]USB: {name} {model}({sn})")
elif mvcc_dev_info.nTLayerType == MV_GENTL_CAMERALINK_DEVICE:
info = mvcc_dev_info.SpecialInfo.stCMLInfo
name = decoding_char(info.chUserDefinedName)
model = decoding_char(info.chModelName)
sn = "".join(chr(c) for c in info.chSerialNumber if c != 0)
devList.append(f"[{i}]CML: {name} {model}({sn})")
elif mvcc_dev_info.nTLayerType == MV_GENTL_CXP_DEVICE:
info = mvcc_dev_info.SpecialInfo.stCXPInfo
name = decoding_char(info.chUserDefinedName)
model = decoding_char(info.chModelName)
sn = "".join(chr(c) for c in info.chSerialNumber if c != 0)
devList.append(f"[{i}]CXP: {name} {model}({sn})")
elif mvcc_dev_info.nTLayerType == MV_GENTL_XOF_DEVICE:
info = mvcc_dev_info.SpecialInfo.stXoFInfo
name = decoding_char(info.chUserDefinedName)
model = decoding_char(info.chModelName)
sn = "".join(chr(c) for c in info.chSerialNumber if c != 0)
devList.append(f"[{i}]XoF: {name} {model}({sn})")
ui.ComboDevices.clear()
ui.ComboDevices.addItems(devList)
ui.ComboDevices.setCurrentIndex(0)
def open_device():
global deviceList, nSelCamIndex, obj_cam_operation, isOpen
if isOpen:
QMessageBox.warning(mainWindow, "Error", 'Camera is Running!', QMessageBox.Ok)
return MV_E_CALLORDER
nSelCamIndex = ui.ComboDevices.currentIndex()
if nSelCamIndex < 0:
QMessageBox.warning(mainWindow, "Error", 'Please select a camera!', QMessageBox.Ok)
return MV_E_CALLORDER
obj_cam_operation = CameraOperation(cam, deviceList, nSelCamIndex)
ret = obj_cam_operation.Open_device()
if ret != 0:
QMessageBox.warning(mainWindow, "Error", "Open device failed ret:" + ToHexStr(ret), QMessageBox.Ok)
isOpen = False
else:
set_continue_mode()
isOpen = True
enable_controls()
def start_grabbing():
"""
Starts the camera stream AND launches the GO/NO-GO processor thread.
The processor reads frames independently; results are pushed to the
overlay widget every 100 ms via ui_refresh_timer.
"""
global obj_cam_operation, isGrabbing, gonogo_processor
# ret = obj_cam_operation.Start_grabbing(ui.widgetDisplay.winId())
ret = obj_cam_operation.Start_grabbing(0)
if ret != 0:
QMessageBox.warning(mainWindow, "Error", "Start grabbing failed ret:" + ToHexStr(ret), QMessageBox.Ok)
return
isGrabbing = True
enable_controls()
# Start GO/NO-GO background processor
gonogo_processor = GoNoGoProcessor(obj_cam_operation, _on_gonogo_result)
gonogo_processor.start()
# Refresh UI every 100 ms (10 fps display update for overlay)
ui_refresh_timer.start(100)
overlay_widget.update_result("DETECTING...", 0, None, None)
print("[GO/NOGO] Processor started.")
def stop_grabbing():
global obj_cam_operation, isGrabbing, gonogo_processor
global is_debug_save_enabled
is_debug_save_enabled = False
ui.bnSaveImage.setText("Save Image")
ui.bnSaveImage.setStyleSheet("")
# Stop GO/NO-GO processor first
if gonogo_processor is not None:
gonogo_processor.stop()
ui_refresh_timer.stop()
overlay_widget.update_result("WAITING", 0, None, None)
ret = obj_cam_operation.Stop_grabbing()
if ret != 0:
QMessageBox.warning(mainWindow, "Error", "Stop grabbing failed ret:" + ToHexStr(ret), QMessageBox.Ok)
else:
isGrabbing = False
enable_controls()
print("[GO/NOGO] Processor stopped.")
def close_device():
global isOpen, isGrabbing, obj_cam_operation, gonogo_processor
global is_debug_save_enabled
is_debug_save_enabled = False
ui.bnSaveImage.setText("Save Image")
ui.bnSaveImage.setStyleSheet("")
if gonogo_processor is not None:
gonogo_processor.stop()
ui_refresh_timer.stop()
if isOpen:
obj_cam_operation.Close_device()
isOpen = False
isGrabbing = False
enable_controls()
def set_continue_mode():
ret = obj_cam_operation.Set_trigger_mode(False)
if ret != 0:
QMessageBox.warning(mainWindow, "Error", "Set continue mode failed ret:" + ToHexStr(ret), QMessageBox.Ok)
else:
ui.radioContinueMode.setChecked(True)
ui.radioTriggerMode.setChecked(False)
ui.bnSoftwareTrigger.setEnabled(False)
def set_software_trigger_mode():
ret = obj_cam_operation.Set_trigger_mode(True)
if ret != 0:
QMessageBox.warning(mainWindow, "Error", "Set trigger mode failed ret:" + ToHexStr(ret), QMessageBox.Ok)
else:
ui.radioContinueMode.setChecked(False)
ui.radioTriggerMode.setChecked(True)
ui.bnSoftwareTrigger.setEnabled(isGrabbing)
def trigger_once():
ret = obj_cam_operation.Trigger_once()
if ret != 0:
QMessageBox.warning(mainWindow, "Error", "TriggerSoftware failed ret:" + ToHexStr(ret), QMessageBox.Ok)
def save_bmp():
global is_debug_save_enabled
is_debug_save_enabled = not is_debug_save_enabled