-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1556 lines (1437 loc) · 64 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
#!/usr/bin/python
# -*- coding:utf-8 -*-
# @File : main.py
# @Author : Wang Weijian
# @Time : 2023/09/12 09:57:48
# @function: The main program run by AiKit 3D UI
# @version : V1.0
import os
import random
import sys
import threading
import time
import traceback
import cv2
import numpy as np
import serial
import serial.tools.list_ports
from PyQt6.QtCore import Qt, pyqtSlot, QDateTime, QRegularExpression, QThread, pyqtSignal
from PyQt6.QtGui import QPixmap, QRegularExpressionValidator, QImage
from PyQt6.QtWidgets import QMainWindow, QWidget, QApplication, QMessageBox
from pymycobot.mecharm270 import MechArm270
from Utils.coord_calc import CoordCalc
sys.path.append(os.getcwd())
from resources.ui.AiKit_3D import Ui_AiKit_UI as AiKit_window
from resources.log.logfile import MyLogging
from configs.all_config import *
from Utils.arm_controls import *
from detect.shape_detect import ShapeDetector
from detect.color_detect import ColorDetector
from detect.yolov8_detect import YOLODetector
from ObbrecCamera import ObbrecCamera
from Utils.crop_tools import crop_frame, crop_poly
class AiKit_App(AiKit_window, QMainWindow, QWidget):
def __init__(self):
super(AiKit_App, self).__init__()
self.setupUi(self)
# 去掉窗口顶部边框
self.setWindowFlag(Qt.WindowType.FramelessWindowHint)
self.min_btn.clicked.connect(self.min_clicked)
self.close_btn.clicked.connect(self.close_clicked)
self.language_btn.clicked.connect(self.set_language)
self.comboBox_function.highlighted.connect(self.choose_function)
self.comboBox_function.activated.connect(self.choose_function)
self.comboBox_port.highlighted.connect(self.get_serial_port_list)
self.comboBox_port.activated.connect(self.get_serial_port_list)
self.comboBox_baud.highlighted.connect(self.baud_choose)
self.comboBox_baud.activated.connect(self.baud_choose)
self.connect_btn.clicked.connect(self.connect_checked)
self.to_origin_btn.clicked.connect(self.go_home_function)
self.offset_save_btn.clicked.connect(self.insert_offset)
self.discern_btn.clicked.connect(self.discern_function)
self.crawl_btn.clicked.connect(self.crawl_function)
self.place_btn.clicked.connect(self.place_function)
self.current_coord_btn.clicked.connect(self.get_current_coords_btn)
self.image_coord_btn.clicked.connect(self.get_img_coords_btn)
self.open_camera_btn.clicked.connect(self.camera_checked)
self.M5 = ['mechArm 270 for M5']
self.mc = None
self.port_list = []
self.logger = MyLogging().logger
self.offset_x, self.offset_y, self.offset_z = 0, 0, 0
self.pos_x, self.pos_y, self.pos_z = 0, 0, 0
# 记录鼠标按下时的位置
self.dragPos = None
self.lastTime = None
self.language = 1 # Control language, 1 is English, 2 is Chinese
if self.language == 1:
self.btn_color(self.language_btn, 'green')
else:
self.btn_color(self.language_btn, 'blue')
self.is_language_btn_click = False
self.is_go_home = False
self.is_discern = False
self.is_crawl = False
self.is_place = False
self.is_pick = True
self.is_current_coords = False
self.is_img_coords = False
self.is_open_camera = False
self.is_connected = False
self.radioButton_A.setChecked(True)
self.color_frame = None
self.depth_frame = None
self.algorithm_mode = None
self.open_camera = None
self.detect_thread = None
self.show_camera_lab_depth.hide()
self.show_camera_lab_rgb.hide()
# 创建一个锁对象
self.crawl_move_lock = threading.Lock()
self.is_thread_running = True
self.algorithm_pump = ['Color recognition pump', 'Shape recognition pump', 'yolov8 pump', 'Depalletizing pump',
'颜色识别 吸泵', '形状识别 吸泵', 'yolov8 吸泵', '拆码垛 吸泵']
self.algorithm_gripper = ['Color recognition gripper', 'yolov8 gripper', '颜色识别 夹爪', 'yolov8 夹爪']
self._init_main_window()
self.choose_function()
self.get_serial_port_list()
self.baud_choose()
self.init_btn_status(False)
self.init_offset_tooltip()
self.offset_change()
def _init_main_window(self):
"""
加载窗口logo图标、最小化按钮图标、关闭按钮图标
Returns: None
"""
try:
self.pix = QPixmap(libraries_path + '/img/logo.ico') # the path to the icon
self.logo_lab.setPixmap(self.pix)
self.logo_lab.setScaledContents(True)
# Close, minimize button display text
self.min_btn.setStyleSheet("border-image: url({}/img/min.ico);".format(libraries_path))
self.close_btn.setStyleSheet("border-image: url({}/img/close.ico);".format(libraries_path))
except Exception as e:
e = traceback.format_exc()
self.logger.error(str(e))
@pyqtSlot()
def close_clicked(self):
self.close()
QApplication.instance().quit()
@pyqtSlot()
def min_clicked(self):
# minimize
self.showMinimized()
def mousePressEvent(self, event):
if event.buttons() == Qt.MouseButton.LeftButton and event.pos().y() < 50:
self.dragPos = event.pos()
self.lastTime = QDateTime.currentDateTime()
def mouseMoveEvent(self, event):
"""添加一个计时器,限制窗口移动的最小时间间隔,从而减少窗口抖动的问题"""
if self.dragPos is not None and self.lastTime is not None:
currentTime = QDateTime.currentDateTime()
elapsedTime = self.lastTime.msecsTo(currentTime)
if elapsedTime >= 10: # 限制窗口移动的最小时间间隔
delta = event.pos() - self.dragPos
self.move(self.pos() + delta)
self.lastTime = currentTime
event.accept()
self.setCursor(Qt.CursorShape.OpenHandCursor)
def mouseReleaseEvent(self, event):
self.dragPos = None
self.lastTime = None
self.setCursor(Qt.CursorShape.ArrowCursor)
def btn_color(self, btn, color):
"""
设置按钮的颜色样式
Args:
btn: 按钮名称
color: 颜色名称
Returns: None
"""
try:
if color == 'red':
btn.setStyleSheet("background-color: rgb(231, 76, 60);\n"
"color: rgb(255, 255, 255);\n"
"border-radius: 10px;\n"
"border: 2px groove gray;\n"
"border-style: outset;")
elif color == 'green':
btn.setStyleSheet("background-color: rgb(39, 174, 96);\n"
"color: rgb(255, 255, 255);\n"
"border-radius: 10px;\n"
"border: 2px groove gray;\n"
"border-style: outset;")
elif color == 'blue':
btn.setStyleSheet("background-color: rgb(41, 128, 185);\n"
"color: rgb(255, 255, 255);\n"
"border-radius: 10px;\n"
"border: 2px groove gray;\n"
"border-style: outset;")
elif color == 'gray':
btn.setStyleSheet("background-color: rgb(185, 195, 199);\n"
"color: rgb(255, 255, 255);\n"
"border-radius: 10px;\n"
"border: 2px groove gray;\n"
"border-style: outset;")
except Exception as e:
e = traceback.format_exc()
self.logger.error(str(e))
def set_language(self):
"""
设置语言
"""
try:
self.is_language_btn_click = True
if self.language == 1:
self.language = 2
self.btn_color(self.language_btn, 'blue')
else:
self.language = 1
self.btn_color(self.language_btn, 'green')
self._init_language()
self.choose_function()
self.is_language_btn_click = False
self.init_offset_tooltip()
except Exception as e:
e = traceback.format_exc()
self.logger.error(str(e))
def _init_language(self):
"""
初始化语言
"""
if self.language == 1:
if not self.is_language_btn_click:
return
self.camara_show.setText("Camera")
if self.open_camera_btn.text() == '打开':
self.open_camera_btn.setText("Open")
else:
self.open_camera_btn.setText("Close")
self.connect_lab.setText("Connection")
if self.connect_btn.text() == '连接':
self.connect_btn.setText("CONNECT")
else:
self.connect_btn.setText("DISCONNECT")
self.device_lab.setText("Device")
self.baud_lab.setText("Baud")
self.port_lab.setText("Serial Port")
self.control_lab.setText("Control")
self.to_origin_btn.setText("Go")
self.home_lab.setText("Homing")
self.recognition_lab.setText("Recognition")
self.discern_btn.setText("Run")
self.offsets_lab.setText("XYZ Offset")
self.current_algorithm_lab.setText("Current Algorithm:")
self.crawl_btn.setText("Run")
self.pick_lab.setText("Pick")
self.place_lab.setText("Place")
self.place_btn.setText('Run')
self.offset_save_btn.setText('Save')
self.algorithm_lab2.setText("Algorithm")
self.select_lab.setText("Select")
self.comboBox_function.setItemText(0, "Color recognition pump")
self.comboBox_function.setItemText(1, "Shape recognition pump")
self.comboBox_function.setItemText(2, "yolov8 pump")
self.comboBox_function.setItemText(3, "Depalletizing pump")
self.comboBox_function.setItemText(4, "Color recognition gripper")
self.comboBox_function.setItemText(5, "yolov8 gripper")
self.display_lab.setText("Display")
self.current_coord_btn.setText("current coordinates")
self.image_coord_btn.setText("image coordinates")
self.language_btn.setText("简体中文")
self.show_camera_lab_depth.setText("Camera Depth Screen")
self.show_camera_lab_rgb.setText("Camera Color Screen")
else:
self.camara_show.setText("相机")
if self.is_language_btn_click:
if self.open_camera_btn.text() == 'Open':
self.open_camera_btn.setText("打开")
else:
self.open_camera_btn.setText("关闭")
else:
self.open_camera_btn.setText("打开")
self.connect_lab.setText("连接")
if self.is_language_btn_click:
if self.connect_btn.text() == 'CONNECT':
self.connect_btn.setText("连接")
else:
self.connect_btn.setText("断开")
else:
self.connect_btn.setText("连接")
self.device_lab.setText("设备")
self.baud_lab.setText("波特率")
self.port_lab.setText("串口")
self.control_lab.setText("控制")
self.to_origin_btn.setText("运行")
self.home_lab.setText("初始点")
self.recognition_lab.setText("识别")
self.discern_btn.setText("运行")
self.offsets_lab.setText("XYZ 偏移量")
self.current_algorithm_lab.setText("当前算法:")
self.crawl_btn.setText("运行")
self.pick_lab.setText("抓取")
self.place_lab.setText("放置")
self.place_btn.setText("运行")
self.offset_save_btn.setText("保存")
self.algorithm_lab2.setText("算法")
self.select_lab.setText("选择")
self.comboBox_function.setItemText(0, "颜色识别 吸泵")
self.comboBox_function.setItemText(1, "形状识别 吸泵")
self.comboBox_function.setItemText(2, "yolov8 吸泵")
self.comboBox_function.setItemText(3, "拆码垛 吸泵")
self.comboBox_function.setItemText(4, "颜色识别 夹爪")
self.comboBox_function.setItemText(5, "yolov8 夹爪")
self.display_lab.setText("坐标显示")
self.current_coord_btn.setText("实时坐标")
self.image_coord_btn.setText("图像坐标")
self.language_btn.setText("English")
self.show_camera_lab_depth.setText("相机深度画面")
self.show_camera_lab_rgb.setText("相机彩色画面")
def init_btn_status(self, status):
"""
初始化各个按钮的状态
Args:
status: bool类型(True/False)
Returns: None
"""
try:
btn_list = [self.to_origin_btn, self.crawl_btn, self.place_btn, self.current_coord_btn,
self.image_coord_btn, self.discern_btn, self.open_camera_btn]
btn_list2 = [self.to_origin_btn]
green_btn = [self.open_camera_btn, self.current_coord_btn, self.image_coord_btn]
if status:
for b in btn_list2:
b.setEnabled(True)
self.btn_color(b, 'blue')
# for c in green_btn:
# c.setEnabled(True)
# self.btn_color(c, 'green')
else:
for b in btn_list:
b.setEnabled(False)
self.btn_color(b, 'gray')
except Exception as e:
e = traceback.format_exc()
self.logger.error(str(e))
def choose_function(self):
"""
根据算法下拉框选择显示当前算法名称,使用正则表达式限制偏移量的输入类型及其范围
Returns: None
"""
try:
self.algorithm_mode = self.comboBox_function.currentText()
self.algorithm_lab.setText(self.algorithm_mode)
self.xoffset_edit.setEnabled(True)
self.yoffset_edit.setEnabled(True)
self.zoffset_edit.setEnabled(True)
self.is_pick = True
# 偏移量设置正则表达式校验器,只允许输入-255 到 255数字
regex = QRegularExpression(r'^-?(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$')
validator = QRegularExpressionValidator(regex)
edit_widgets = [self.xoffset_edit, self.yoffset_edit, self.zoffset_edit]
for edit_widget in edit_widgets:
edit_widget.setValidator(validator)
self.offset_change()
if self.algorithm_mode in ['Depalletizing pump', '拆码垛 吸泵']:
self.place_btn.setEnabled(False)
self.btn_color(self.place_btn, 'gray')
else:
if self.is_connected:
self.place_btn.setEnabled(False)
self.btn_color(self.place_btn, 'gray')
except Exception as e:
e = traceback.format_exc()
self.logger.error(str(e))
def get_serial_port_list(self):
"""
获取当前串口号并映射到串口下拉框
Returns: 串口号
"""
plist = [
str(x).split(" - ")[0].strip() for x in serial.tools.list_ports.comports()
]
print(plist)
try:
if not plist:
# if self.comboBox_port.currentText() == 'no port':
# return
self.comboBox_port.clear()
self.comboBox_port.addItem('no port')
self.connect_btn.setEnabled(False)
self.btn_color(self.connect_btn, 'gray')
self.port_list = []
return
else:
if self.port_list != plist:
self.port_list = plist
self.comboBox_port.clear()
self.connect_btn.setEnabled(True)
self.btn_color(self.connect_btn, 'green')
for p in plist:
self.comboBox_port.addItem(p)
except Exception as e:
e = traceback.format_exc()
self.logger.error(str(e))
def baud_choose(self):
"""
根据机器设备选择正确的串口号
Returns: None
"""
device = self.comboBox_device.currentText()
if device in self.M5:
self.comboBox_baud.setCurrentIndex(0)
else:
self.comboBox_baud.setCurrentIndex(1)
def connect_checked(self):
"""
连接按钮的状态切换
Returns:
"""
try:
if self.language == 1:
txt = 'CONNECT'
else:
txt = '连接'
if self.connect_btn.text() == txt:
self.robotics_connect()
else:
self.disconnect_robotics()
except Exception as e:
e = traceback.format_exc()
self.logger.error(str(e))
def robotics_connect(self):
"""
启动机械臂连接的子线程
Returns: None
"""
try:
self.prompts_lab.clear()
device = self.comboBox_device.currentText()
if device == 'mechArm 270 for M5':
init_robotics = threading.Thread(target=self.init_270_M5)
init_robotics.start()
except Exception as e:
e = traceback.format_exc()
self.logger.error(str(e))
def init_270_M5(self):
"""
连接机械臂,并对机械臂进行一些初始化
Returns:
"""
try:
self.comboBox_device.setEnabled(False)
self.comboBox_baud.setEnabled(False)
self.comboBox_port.setEnabled(False)
port = self.comboBox_port.currentText()
baud = self.comboBox_baud.currentText()
self.algorithm_mode = self.comboBox_function.currentText()
self.mc = MechArm270(port, baud)
time.sleep(0.1)
self.logger.info('connection succeeded !')
self.is_connected = True
self.init_btn_status(True)
self.current_coord_btn.setEnabled(True)
self.btn_color(self.current_coord_btn, 'green')
if self.language == 1:
self.connect_btn.setText('Disconnect')
else:
self.connect_btn.setText('断开')
self.btn_color(self.connect_btn, 'red')
except Exception as e:
e = traceback.format_exc()
error_mes = 'Connection failed !!!:{}'.format(e)
self.mc = None
self.is_connected = False
self.comboBox_port.setEnabled(True)
self.comboBox_baud.setEnabled(False)
self.comboBox_device.setEnabled(True)
self.init_btn_status(False)
if self.language == 1:
self.connect_btn.setText('CONNECT')
else:
self.connect_btn.setText('连接')
self.btn_color(self.connect_btn, 'green')
self.logger.error(error_mes)
def has_mycobot(self):
"""
检查机械臂是否连接
Returns:
"""
if not self.mc:
self.logger.info("Mycobot is not connected yet! ! ! Please connect to myCobot first! ! !")
return False
return True
def disconnect_robotics(self):
"""
机械臂断开连接
Returns: None
"""
if not self.has_mycobot():
return
try:
time.sleep(0.1)
del self.mc
self.mc = None
self.logger.info("Disconnected successfully !")
self.is_connected = False
self.comboBox_port.setEnabled(True)
self.comboBox_baud.setEnabled(True)
self.comboBox_device.setEnabled(True)
self.comboBox_function.setEnabled(True)
if self.language == 1:
self.connect_btn.setText('CONNECT')
else:
self.connect_btn.setText('连接')
self.btn_color(self.connect_btn, 'green')
self.init_btn_status(False)
self.is_discern = False
self.is_current_coords = False
self.is_place = False
self.is_crawl = False
self.is_img_coords = False
self.current_coord_lab.clear()
self.img_coord_lab.clear()
self.prompts_lab.clear()
self.show_camera_lab_depth.hide()
self.show_camera_lab_rgb.hide()
except Exception as e:
e = traceback.format_exc()
self.logger.info("Not yet connected to mycobot!!!{}".format(str(e)))
def robot_go_home(self):
"""
控制机械臂回到初始点 [-90, 0, 0, 0, 90, 0]
Returns: None
"""
try:
self.mc.set_fresh_mode(0)
time.sleep(0.5)
device = self.comboBox_device.currentText()
go_home_mes = 'The robot moves to the initial point'
if device in self.M5:
self.logger.info(go_home_mes)
self.mc.send_angles(arm_idle_angle, 50)
time.sleep(3)
if self.algorithm_mode in self.algorithm_pump:
self.mc.set_tool_reference(tool_frame_pump)
time.sleep(0.5)
self.mc.set_end_type(1)
time.sleep(1)
pump_off(self.mc)
time.sleep(1.5)
else:
self.mc.set_tool_reference(tool_frame_gripper)
time.sleep(0.5)
self.mc.set_end_type(1)
time.sleep(1)
open_gripper(self.mc)
time.sleep(2)
print('open gripper')
release_gripper(self.mc)
time.sleep(0.1)
self.is_go_home = False
self.btn_color(self.to_origin_btn, 'blue')
if not self.is_discern:
self.discern_btn.setEnabled(True)
self.btn_color(self.discern_btn, 'blue')
except Exception as e:
e = traceback.format_exc()
self.logger.error(str(e))
def go_home_function(self):
"""
回到初始点和初始化参数 按钮开关
Returns: None
"""
try:
if self.is_go_home:
self.is_go_home = False
self.btn_color(self.to_origin_btn, 'blue')
else:
self.is_go_home = True
self.btn_color(self.to_origin_btn, 'red')
go_home = threading.Thread(target=self.robot_go_home)
go_home.start()
except Exception as e:
e = traceback.format_exc()
self.logger.error(str(e))
def init_offset_tooltip(self):
"""
鼠标悬浮在 XYZ Offsets 控件上的提示功能作用
Returns: None
"""
try:
if self.language == 1:
self.offsets_lab.setToolTip(
'Adjust the suction position of the end, add X forward,'
' subtract X backward, \nadd Y to the left, and subtract Y to the right, decrease Z downward, and increase Z upward')
else:
self.offsets_lab.setToolTip(
'调整末端吸取位置,向前X加,向后X减,向左Y加,向右Y减,向下Z减,向上Z加。')
except Exception as e:
e = traceback.format_exc()
self.logger.error(str(e))
def offset_change(self):
"""
根据算法功能的不同,从文件中读取偏移量信息并将其显示在对应的文本框中
Returns: None
"""
try:
self.algorithm_mode = self.comboBox_function.currentText()
# 定义文件路径与功能的映射关系
file_paths = {
'颜色识别 吸泵': 'color_pump_offset.txt',
'Color recognition pump': 'color_pump_offset.txt',
'形状识别 吸泵': 'shape_pump_offset.txt',
'Shape recognition pump': 'shape_pump_offset.txt',
'yolov8 吸泵': 'yolo_pump_offset.txt',
'yolov8 pump': 'yolo_pump_offset.txt',
'拆码垛 吸泵': 'pallet_pump_offset.txt',
'Depalletizing pump': 'pallet_pump_offset.txt',
'颜色识别 夹爪': 'color_gripper_offset.txt',
'Color recognition gripper': 'color_gripper_offset.txt',
'yolov8 夹爪': 'yolo_gripper_offset.txt',
'yolov8 gripper': 'yolo_gripper_offset.txt',
}
file_path = file_paths.get(self.algorithm_mode)
if file_path:
with open(libraries_path + '/offset/' + file_path, 'r', encoding='utf-8') as f:
offset = f.read().splitlines()
offset_values = eval(offset[0])
self.offset_x, self.offset_y, self.offset_z = map(int, offset_values)
self.xoffset_edit.clear()
self.yoffset_edit.clear()
self.zoffset_edit.clear()
self.xoffset_edit.setText(f'{offset_values[0]}')
self.yoffset_edit.setText(f'{offset_values[1]}')
self.zoffset_edit.setText(f'{offset_values[2]}')
except Exception as e:
e = traceback.format_exc()
self.logger.error(str(e))
def insert_offset(self):
"""
读取XYZ偏移量的值,并保存到对应文件中
Returns: None
"""
try:
self.algorithm_mode = self.comboBox_function.currentText()
x = self.xoffset_edit.text()
y = self.yoffset_edit.text()
z = self.zoffset_edit.text()
offset = [x, y, z]
file_paths = {
'颜色识别 吸泵': 'color_pump_offset.txt',
'Color recognition pump': 'color_pump_offset.txt',
'形状识别 吸泵': 'shape_pump_offset.txt',
'Shape recognition pump': 'shape_pump_offset.txt',
'yolov8 吸泵': 'yolo_pump_offset.txt',
'yolov8 pump': 'yolo_pump_offset.txt',
'拆码垛 吸泵': 'pallet_pump_offset.txt',
'Depalletizing pump': 'pallet_pump_offset.txt',
'颜色识别 夹爪': 'color_gripper_offset.txt',
'Color recognition gripper': 'color_gripper_offset.txt',
'yolov8 夹爪': 'yolo_gripper_offset.txt',
'yolov8 gripper': 'yolo_gripper_offset.txt',
}
file_path = file_paths.get(self.algorithm_mode)
if file_path:
with open(libraries_path + '/offset/' + file_path, 'w', encoding='utf-8') as f:
f.write(str(offset))
self.offset_x, self.offset_y, self.offset_z = int(x), int(y), int(z)
if self.language == 1:
msg_box = QMessageBox(QMessageBox.Icon.Information, 'prompt', 'Successfully saved!')
else:
msg_box = QMessageBox(QMessageBox.Icon.Information, '提示', '保存成功!')
msg_box.exec()
except Exception as e:
e = traceback.format_exc()
self.logger.error(str(e))
def discern_function(self):
"""
识别按钮的开关, 如果打开识别按钮则可以打开摄像头按钮,以及点击查看图像按钮,如果关闭识别按钮,则摄像头打开按钮复位变绿色
Returns: None
"""
try:
if self.is_discern:
self.is_discern = False
self.btn_color(self.discern_btn, 'blue')
self.stop_thread()
self.open_camera.release()
self.detect_thread.join()
self.open_camera = None
self.is_thread_running = True
self.is_open_camera = False
self.show_camera_lab_depth.clear()
self.show_camera_lab_rgb.clear()
if self.language == 1:
self.open_camera_btn.setText('Open')
else:
self.open_camera_btn.setText('打开')
self.prompts_lab.clear()
self.open_camera_btn.setEnabled(False)
self.image_coord_btn.setEnabled(False)
self.crawl_btn.setEnabled(False)
self.btn_color(self.crawl_btn, 'gray')
self.place_btn.setEnabled(False)
self.btn_color(self.place_btn, 'gray')
self.btn_color(self.open_camera_btn, 'gray')
self.btn_color(self.image_coord_btn, 'gray')
self.img_coord_lab.clear()
self.is_img_coords = False
self.comboBox_function.setEnabled(True)
else:
self.prompts_lab.clear()
self.is_discern = True
self.btn_color(self.discern_btn, 'red')
self.open_camera_btn.setEnabled(True)
self.image_coord_btn.setEnabled(True)
self.crawl_btn.setEnabled(True)
self.btn_color(self.crawl_btn, 'blue')
self.btn_color(self.open_camera_btn, 'green')
self.btn_color(self.image_coord_btn, 'green')
self.show_camera_lab_depth.hide()
self.show_camera_lab_rgb.hide()
self.comboBox_function.setEnabled(False)
run_detect = threading.Thread(target=self.start_detect)
run_detect.start()
except Exception as e:
e = traceback.format_exc()
self.logger.error('identify anomalies' + str(e))
def crawl_function(self):
"""
抓取物体-运行按钮的开关
Returns: None
"""
try:
self.algorithm_mode = self.comboBox_function.currentText()
if self.is_crawl:
self.is_crawl = False
self.btn_color(self.crawl_btn, 'blue')
if self.algorithm_mode in ['Depalletizing pump', '拆码垛 吸泵']:
self.pallet.join()
else:
self.is_crawl = True
self.btn_color(self.crawl_btn, 'red')
if self.algorithm_mode in ['Depalletizing pump', '拆码垛 吸泵']:
self.pallet = threading.Thread(target=self.start_pallet_crawl)
self.pallet.start()
else:
self.place_btn.setEnabled(True)
self.btn_color(self.place_btn, 'blue')
crawl_move = threading.Thread(target=self.robot_pick_move)
crawl_move.start()
except Exception as e:
e = traceback.format_exc()
self.logger.error(str(e))
def place_function(self):
"""
放置按钮的开关
Returns: None
"""
try:
if self.is_place:
self.is_place = False
self.btn_color(self.place_btn, 'blue')
else:
self.is_place = True
self.btn_color(self.place_btn, 'red')
# self.robot_place_move()
place_move = threading.Thread(target=self.robot_place_move)
place_move.start()
except Exception as e:
e = traceback.format_exc()
self.logger.error(str(e))
def get_current_coords(self):
"""
获取当前机械臂的坐标,并更新坐标的显示
Returns: None
"""
while self.is_current_coords:
QApplication.processEvents()
try:
coord = self.mc.get_coords()
except Exception as e:
e = traceback.format_exc()
coord = []
self.logger.error(str(e))
pass
if coord and len(coord) == 6:
coord = 'X: {} Y: {} Z: {} Rx: {} Ry: {} Rz: {}'.format(coord[0], coord[1], coord[2], coord[3],
coord[4],
coord[5])
if self.is_current_coords:
self.current_coord_lab.clear()
self.current_coord_lab.setText(str(coord))
time.sleep(0.2)
def get_current_coords_btn(self):
"""
通过点击按钮,显示当前机械臂的坐标开关
Returns: None
"""
try:
if not self.has_mycobot():
return
if self.is_current_coords:
self.is_current_coords = False
self.btn_color(self.current_coord_btn, 'green')
self.current_coord_lab.clear()
else:
self.is_current_coords = True
self.btn_color(self.current_coord_btn, 'red')
get_coord = threading.Thread(target=self.get_current_coords)
get_coord.start()
except Exception as e:
e = traceback.format_exc()
self.logger.error(str(e))
def get_img_coords_btn(self):
"""
获取图像的定位坐标
Returns: None
"""
try:
if self.is_img_coords:
self.is_img_coords = False
self.btn_color(self.image_coord_btn, 'green')
self.img_coord_lab.clear()
else:
self.is_img_coords = True
if self.is_discern:
self.btn_color(self.image_coord_btn, 'red')
get_img = threading.Thread(target=self.get_img_coords)
get_img.start()
except Exception as e:
e = traceback.format_exc()
self.logger.error(str(e))
def get_img_coords(self):
while self.is_img_coords:
QApplication.processEvents()
try:
if self.is_discern:
if self.is_img_coords:
self.img_coord_lab.clear()
self.img_coord_lab.setText(str('X: {} Y: {} Z: {}'.format(self.pos_x, self.pos_y, self.pos_z)))
time.sleep(0.1)
else:
if self.language == 2:
self.img_coord_lab.setText('请先启动识别程序!')
else:
self.img_coord_lab.setText('Please start the recognition process first!')
except Exception as e:
e = traceback.format_exc()
self.logger.error(str(e))
def display_open_camera_1(self, detector):
"""
开启摄像头并将画面显示在界面上(适用于颜色识别、形状识别)
Args:
detector: 一个识别算法检测类
Returns: None
"""
print('Start Color or Shape......')
self.algorithm_mode = self.comboBox_function.currentText()
if not self.is_open_camera:
self.open_camera = ObbrecCamera()
self.open_camera.capture()
self.is_open_camera = True
while self.is_thread_running:
self.open_camera.update_frame()
color_frame = self.open_camera.color_frame()
depth_frame = self.open_camera.depth_frame()
if color_frame is None or depth_frame is None:
# time.sleep(0.1)
continue
color_frame = crop_frame(color_frame, crop_size, crop_offset)
depth_frame = crop_frame(depth_frame, crop_size, crop_offset)
depth_visu_frame = depth_frame.copy()
color_frame = cv2.resize(color_frame, None, fx=zoom_factor, fy=zoom_factor)
depth_frame = cv2.resize(depth_frame, None, fx=zoom_factor, fy=zoom_factor)
if color_frame is not None:
depth_visu_frame = depth_visu_frame / np.max(depth_frame) * 255
depth_visu_frame = depth_visu_frame.astype(np.uint8)
depth_visu_frame = cv2.cvtColor(depth_visu_frame, cv2.COLOR_GRAY2BGR)
# Convert BGR to RGB
color_frame_qt = cv2.cvtColor(color_frame, cv2.COLOR_BGR2RGB)
color_frame_qimage = QImage(
color_frame_qt.data,
color_frame_qt.shape[1],
color_frame_qt.shape[0],
color_frame_qt.strides[0],
QImage.Format.Format_RGB888,
)
depth_frame_qimage = QImage(
depth_visu_frame.data,
depth_visu_frame.shape[1],
depth_visu_frame.shape[0],
depth_visu_frame.strides[0],
QImage.Format.Format_RGB888,
)
# Create QPixmap from QImage
color_pixmap = QPixmap.fromImage(color_frame_qimage)
depth_pixmap = QPixmap.fromImage(depth_frame_qimage)
# Set the QPixmap to QLabel
self.show_camera_lab_rgb.setPixmap(color_pixmap)
self.show_camera_lab_depth.setPixmap(depth_pixmap.scaled(390, 390))
if color_frame is None:
continue
res = detector.detect(color_frame)
if res:
if self.is_pick:
# 获取检测到的颜色名称
detector.draw_result(color_frame, res)
# Convert BGR to RGB
color_frame_qt = cv2.cvtColor(color_frame, cv2.COLOR_BGR2RGB)
color_frame_qimage = QImage(
color_frame_qt.data,
color_frame_qt.shape[1],
color_frame_qt.shape[0],
color_frame_qt.strides[0],
QImage.Format.Format_RGB888,
)
color_pixmap = QPixmap.fromImage(color_frame_qimage)
self.show_camera_lab_rgb.setPixmap(color_pixmap)
# interpret result
obj_configs = []
for obj in res:
rect = detector.get_rect(obj)
x, y = detector.target_position(obj)
obj_configs.append((rect, (x, y)))
# pack (depth, pos, angle) together
depth_pos_pack = []
for obj in obj_configs:
rect, (x, y) = obj
rect = np.array(rect)
target_depth_frame = crop_poly(depth_frame, rect)
mean_depth = np.sum(target_depth_frame) / np.count_nonzero(
target_depth_frame
)
depth_pos_pack.append((mean_depth, (x, y)))
# find lowest depth (highest in pile)
depth, (x, y) = min(depth_pos_pack)
if np.isnan(depth):
self.logger.error('相机无法正确获取深度信息:{}'.format(depth))
continue
else:
x, y = int(x), int(y)
z = int(floor_depth - depth)
# transform angle from camera frame to arm frame
self.pos_x, self.pos_y, self.pos_z = x, y, z
print(f"Raw pos_x,pos_y,pos_z : {self.pos_x} {self.pos_y} {self.pos_z}")
self.logger.info('Recognition has stopped....')
else:
if self.is_open_camera:
try:
self.stop_thread()