-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
2758 lines (2565 loc) · 135 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/env pyhton3
# encoding:utf-8
import math
import os
import sys
import threading
import time
import traceback
import cv2
import numpy as np
import serial
import serial.tools.list_ports
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QPoint, QRegularExpression
from PyQt5.QtCore import pyqtSlot, Qt, QCoreApplication
from PyQt5.QtGui import QEnterEvent, QPixmap, QIntValidator, QRegularExpressionValidator
from PyQt5.QtWidgets import QMainWindow, QApplication, QInputDialog, QWidget, QMessageBox
# from pymycobot.mycobot import MyCobot
# from pymycobot.mypalletizer import MyPalletizer
from pymycobot.ultraArm import ultraArm
from pymycobot.mycobot280 import MyCobot280
from pymycobot.mecharm270 import MechArm270
from pymycobot.mypalletizer260 import MyPalletizer260
from libraries.log import logfile
from libraries.pyqtFile.AiKit_auto import Ui_AiKit_UI as AiKit_window
class AiKit_APP(AiKit_window, QMainWindow, QWidget):
def __init__(self):
super(AiKit_APP, self).__init__()
self.setupUi(self)
self.x1 = self.x2 = self.y1 = self.y2 = 0
# self.M5color.init()
self.myCobot = None
self.loger = logfile.MyLogging().logger
self.path = os.path.split(os.path.abspath(__file__))
self.port_list = []
self.loger = logfile.MyLogging().logger
self._init_main_window()
self._close_max_min_icon()
self._initDrag() # Set the mouse tracking judgment trigger default value
self.setMouseTracking(True) # Set widget mouse tracking
self.widget.installEventFilter(self) # Initialize event filter
self.move(350, 10)
self.radioButton_A.setChecked(True)
self._init_variable()
self._init_status()
self._init_language()
self.cap = cv2.VideoCapture() # video stream
self.min_btn.clicked.connect(self.min_clicked) # minimize
self.max_btn.clicked.connect(self.max_clicked)
self.close_btn.clicked.connect(self.close_clicked) # close
self.comboBox_function.activated.connect(self.combox_func_checked) # switch algorithm
self.comboBox_port.highlighted.connect(self.get_serial_port_list) # get serial port
self.comboBox_port.activated.connect(self.get_serial_port_list) # get serial port
self.comboBox_device.currentTextChanged.connect(self.buad_choose) # Device drop-down box
self.connect_btn.clicked.connect(self.connect_checked) # connect button
self.open_camera_btn.clicked.connect(self.camera_checked) # open/close camera
self.yolov5_cut_btn.clicked.connect(self.cut_yolov5_img)
self.auto_btn.clicked.connect(self.auto_mode) # automation
self.discern_btn.clicked.connect(self.discern_func) # discern
self.crawl_btn.clicked.connect(self.crawl_func) # crawl
self.place_btn.clicked.connect(self.place_func) # place
self.to_origin_btn.clicked.connect(self.to_origin_func) # to_origin
self.offset_save_btn.clicked.connect(self.insert_offsets) # update offsets
self.open_file_btn.clicked.connect(self.open_file) # open file
self.add_img_btn.clicked.connect(self.add_img) # add image
self.exit_add_btn.clicked.connect(self.exit_add) # exit add image
self.image_coord_btn.clicked.connect(self.get_img_coord) # get the image coords
self.current_coord_btn.clicked.connect(self.get_current_coord_btnClick) # get the robot coords
self.language_btn.clicked.connect(self.set_language) # set language
self.get_serial_port_list()
self.offset_change()
self.btn_status()
self.device_coord()
self.cut_yolov5_img_status()
self._init_tooltip()
self.combox_func_checked()
# Initialize variables
def _init_variable(self):
self.pump_y = 0
self.pump_x = 0
# device
self.M5 = ['myPalletizer 260 for M5', 'myCobot 280 for M5', 'ultraArm P340', 'mechArm 270 for M5'] # M5 robot
self.Pi = ['myCobot 280 for Pi', 'mechArm 270 for Pi', 'myCobot 280 for JN',
'myPalletizer 260 for Pi'] # Pi robot
# angles to move
self.move_angles = [
[-29.0, 5.88, -4.92, -76.28], # point to grab
[17.4, -10.1, -87.27, 5.8], # point to grab
]
# origin coords
self.home_coords = [166.4, -21.8, 219, 0.96]
# coords to move
self.move_coords = [
[132.6, -155.6, 211.8, -20.9], # D Sorting area
[232.5, -134.1, 197.7, -45.26], # C Sorting area
[111.6, 159, 221.5, -120], # A Sorting area
[-15.9, 164.6, 217.5, -119.35], # B Sorting area
]
# The internal parameter matrix of the camera
self.camera_matrix = np.array([
[781.33379113, 0., 347.53500524],
[0., 783.79074192, 246.67627253],
[0., 0., 1.]])
# Distortion coefficient of the camera
self.dist_coeffs = np.array(([[3.41360787e-01, -2.52114260e+00, -1.28012469e-03, 6.70503562e-03,
2.57018000e+00]]))
self.color = 0
# parameters to calculate camera clipping parameters 计算相机裁剪参数的参数
self.x1 = self.x2 = self.y1 = self.y2 = 0
# set cache of real coord 设置真实坐标的缓存
self.cache_x = self.cache_y = 0
# set color HSV
self.HSV = {
"yellow": [np.array([11, 85, 70]), np.array([59, 255, 245])],
# "yellow": [np.array([22, 93, 0]), np.array([45, 255, 245])],
"red": [np.array([0, 43, 46]), np.array([8, 255, 255])],
"green": [np.array([35, 43, 35]), np.array([90, 255, 255])],
"blue": [np.array([100, 43, 46]), np.array([124, 255, 255])],
"cyan": [np.array([78, 43, 46]), np.array([99, 255, 255])],
}
# Used to calculate the coordinates between the cube and mycobot
self.sum_x1 = self.sum_x2 = self.sum_y2 = self.sum_y1 = 0
# Grab the coordinates of the center point relative to mycobot
self.camera_x, self.camera_y = 165, 5
self.camera_z = 110
# display real img coord
self.pos_x, self.pos_y, self.pos_z = 0, 0, 0
# The coordinates of the cube relative to mycobot
self.c_x, self.c_y = 0, 0
# The ratio of pixels to actual values
self.ratio = 0
# Get ArUco marker dict that can be detected.
self.aruco_dict = cv2.aruco.Dictionary_get(cv2.aruco.DICT_6X6_250)
# Get ArUco marker params.
self.aruco_params = cv2.aruco.DetectorParameters_create()
# Initialize the background subtractor
self.mog = cv2.bgsegm.createBackgroundSubtractorMOG()
# yolov5 model file path
self.modelWeights = libraries_path + '/yolov5File/yolov5s.onnx'
self._init_ = 20
self.init_num = 0
self.nparams = 0
self.num = 0
self.real_sx = self.real_sy = 0
# Constants.
self.INPUT_WIDTH = 640 # 640
self.INPUT_HEIGHT = 640 # 640
self.SCORE_THRESHOLD = 0.5
self.NMS_THRESHOLD = 0.45
self.CONFIDENCE_THRESHOLD = 0.45
# Text parameters.
self.FONT_FACE = cv2.FONT_HERSHEY_SIMPLEX
self.FONT_SCALE = 0.7
self.THICKNESS = 1
# Colors.
self.BLACK = (0, 0, 0)
self.BLUE = (255, 178, 50)
self.YELLOW = (0, 255, 255)
# initialization status
def _init_status(self):
self.camera_status = False # camera open state
self.discern_status = False # Whether to enable recognition
self.crawl_status = False # Whether to enable crawling
self.place_status = False # Whether to open the placement
self.cut_status = False # Whether to open and cut pictures
self.auto_mode_status = False # Whether to enable automatic operation
self.img_coord_status = False # Whether to enable the display of the X and Y coordinates of the object
self.current_coord_status = False # Whether to enable displaying the real-time location of the robot
self.is_pick = False # Whether the object has been grasped
self.yolov5_is_not_pick = True
self.is_yolov5_cut_btn_clicked = False
self.yolov5_count = False # is first open camera
self.open_camera_func = 1 # Opening mode of the camera, 1 is the open button, 2 is the add button
with open(libraries_path + f'/offset/language.txt', "r", encoding="utf-8") as f:
lange = f.read()
self.language = int(lange) # 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
# Initialize window borders
def _init_main_window(self):
# Set the form to be borderless
self.setWindowFlags(Qt.FramelessWindowHint)
# Set the background to be transparent
self.setAttribute(Qt.WA_TranslucentBackground)
# Set software icon
w = self.logo_lab.width()
h = self.logo_lab.height()
self.pix = QPixmap(libraries_path + '/res/logo.png') # the path to the icon
self.logo_lab.setPixmap(self.pix)
self.logo_lab.setScaledContents(True)
# Close, minimize button display text
def _close_max_min_icon(self):
self.min_btn.setStyleSheet("border-image: url({}/AiKit_UI_img/min.ico);".format(libraries_path))
self.max_btn.setStyleSheet("border-image: url({}/AiKit_UI_img/max.ico);".format(libraries_path))
self.close_btn.setStyleSheet("border-image: url({}/AiKit_UI_img/close.ico);".format(libraries_path))
def _init_tooltip(self):
if self.language == 1:
self.func_lab_6.setToolTip(
'Adjust the suction position of the end, add X forward,'
' subtract X backward, add Y to the left, \nand subtract Y to the right, and Upward Z increases, downward Z decreases.')
else:
self.func_lab_6.setToolTip(
'调整末端吸取位置,向前X加,向后X减,向左Y加,向右Y减,向上Z加,向下Z减。')
@pyqtSlot()
def min_clicked(self):
# minimize
self.showMinimized()
@pyqtSlot()
def max_clicked(self):
# Maximize and restore (not used)
if self.isMaximized():
self.showNormal()
# self.max_btn.setStyleSheet("border-image: url({}/AiKit_UI_img/max.png);".format(libraries_path))
icon_max = QtGui.QIcon()
icon_max.addPixmap(QtGui.QPixmap("./libraries/AiKit_UI_img/max.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.max_btn.setIcon(icon_max)
self.max_btn.setIconSize(QtCore.QSize(30, 30))
self.max_btn.setToolTip("<html><head/><body><p>maximize</p></body></html>")
else:
self.showMaximized()
# self.max_btn.setStyleSheet("border-image: url({}/AiKit_UI_img/nomel.png);".format(libraries_path))
icon_nomel = QtGui.QIcon()
icon_nomel.addPixmap(QtGui.QPixmap("./libraries/AiKit_UI_img/nomel.ico"), QtGui.QIcon.Normal,
QtGui.QIcon.Off)
self.max_btn.setIcon(icon_nomel)
self.max_btn.setIconSize(QtCore.QSize(30, 30))
self.max_btn.setToolTip("<html><head/><body><p>recover</p></body></html>")
@pyqtSlot()
def close_clicked(self):
# turn off an app
if self.camera_status:
self.close_camera()
self.close()
QCoreApplication.instance().quit
def _initDrag(self):
# Set the mouse tracking judgment trigger default value
self._move_drag = False
self._corner_drag = False
self._bottom_drag = False
self._right_drag = False
def eventFilter(self, obj, event):
# Event filter, used to solve the problem of reverting to the standard mouse style after the mouse enters other controls
if isinstance(event, QEnterEvent):
self.setCursor(Qt.ArrowCursor)
return super(AiKit_APP, self).eventFilter(obj, event) # Note that MyWindow is the name of the class
# return QWidget.eventFilter(self, obj, event) # You can also use this, but pay attention to modifying the window type
def resizeEvent(self, QResizeEvent):
# 自定义窗口调整大小事件
# 改变窗口大小的三个坐标范围
self._right_rect = [QPoint(x, y) for x in range(self.width() - 5, self.width() + 5)
for y in range(self.widget.height() + 20, self.height() - 5)]
self._bottom_rect = [QPoint(x, y) for x in range(1, self.width() - 5)
for y in range(self.height() - 5, self.height() + 1)]
self._corner_rect = [QPoint(x, y) for x in range(self.width() - 5, self.width() + 100)
for y in range(self.height() - 5, self.height() + 1)]
def mousePressEvent(self, event):
# 重写鼠标点击的事件
if (event.button() == Qt.LeftButton) and (event.pos() in self._corner_rect):
# 鼠标左键点击右下角边界区域
self._corner_drag = True
event.accept()
elif (event.button() == Qt.LeftButton) and (event.pos() in self._right_rect):
# 鼠标左键点击右侧边界区域
self._right_drag = True
event.accept()
elif (event.button() == Qt.LeftButton) and (event.pos() in self._bottom_rect):
# 鼠标左键点击下侧边界区域
self._bottom_drag = True
event.accept()
elif (event.button() == Qt.LeftButton) and (event.y() < self.widget.height()):
# 鼠标左键点击标题栏区域
self._move_drag = True
self.move_DragPosition = event.globalPos() - self.pos()
event.accept()
def mouseMoveEvent(self, QMouseEvent):
# 判断鼠标位置切换鼠标手势
if QMouseEvent.pos() in self._corner_rect: # QMouseEvent.pos()获取相对位置
self.setCursor(Qt.SizeFDiagCursor)
elif QMouseEvent.pos() in self._bottom_rect:
self.setCursor(Qt.SizeVerCursor)
elif QMouseEvent.pos() in self._right_rect:
self.setCursor(Qt.SizeHorCursor)
# 当鼠标左键点击不放及满足点击区域的要求后,分别实现不同的窗口调整
# 没有定义左方和上方相关的5个方向,主要是因为实现起来不难,但是效果很差,拖放的时候窗口闪烁,再研究研究是否有更好的实现
if Qt.LeftButton and self._right_drag:
# 右侧调整窗口宽度
self.resize(QMouseEvent.pos().x(), self.height())
QMouseEvent.accept()
elif Qt.LeftButton and self._bottom_drag:
# 下侧调整窗口高度
self.resize(self.width(), QMouseEvent.pos().y())
QMouseEvent.accept()
elif Qt.LeftButton and self._corner_drag:
# 由于我窗口设置了圆角,这个调整大小相当于没有用了
# 右下角同时调整高度和宽度
self.resize(QMouseEvent.pos().x(), QMouseEvent.pos().y())
QMouseEvent.accept()
elif Qt.LeftButton and self._move_drag:
# 标题栏拖放窗口位置
self.move(QMouseEvent.globalPos() - self.move_DragPosition)
QMouseEvent.accept()
def mouseReleaseEvent(self, QMouseEvent):
# 鼠标释放后,各扳机复位
self._move_drag = False
self._corner_drag = False
self._bottom_drag = False
self._right_drag = False
self.setCursor(Qt.ArrowCursor)
def has_mycobot(self):
"""Check whether it is connected on mycobot"""
if not self.myCobot:
self.loger.info("Mycobot is not connected yet! ! ! Please connect to myCobot first! ! !")
return False
return True
def get_serial_port_list(self):
"""Get the current serial port and map it to the serial port drop-down box"""
device = self.comboBox_device.currentText()
if device == 'myCobot 280 for JN':
if self.comboBox_port.currentText() != '/dev/ttyTHS1':
self.comboBox_port.addItem('/dev/ttyTHS1')
self.comboBox_port.setCurrentText('/dev/ttyTHS1')
self.port_list = None
self.connect_btn.setEnabled(True)
self.connect_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;")
self.HSV = {
"yellow": [np.array([15, 50, 50]), np.array([50, 255, 255])],
# "yellow": [np.array([22, 93, 0]), np.array([45, 255, 245])],
"red": [np.array([0, 43, 46]), np.array([8, 255, 255])],
"green": [np.array([35, 43, 35]), np.array([90, 255, 255])],
"blue": [np.array([78, 43, 46]), np.array([110, 255, 255])],
"cyan": [np.array([78, 43, 46]), np.array([99, 255, 255])],
}
return
plist = [
str(x).split(" - ")[0].strip() for x in serial.tools.list_ports.comports()
]
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.connect_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;")
self.port_list = []
return
else:
if self.port_list != plist:
self.port_list = plist
self.comboBox_port.clear()
self.connect_btn.setEnabled(True)
self.connect_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;")
for p in plist:
self.comboBox_port.addItem(p)
def buad_choose(self):
try:
"""Switch the baud rate according to the device and initialize the corresponding variable"""
# self.btn_status(True)
value = self.comboBox_device.currentText()
if value in self.Pi:
# self.comboBox_buad.clear()
# self.comboBox_buad.addItem('1000000')
self.comboBox_buad.setCurrentIndex(0)
else:
# self.comboBox_buad.clear()
# self.comboBox_buad.addItem('115200')
self.comboBox_buad.setCurrentIndex(1)
self.get_serial_port_list()
self.offset_change() # Get the corresponding offset of the device
self.device_coord() # Initialize the point of the corresponding device
if value in ['ultraArm P340']:
self.widget_11.hide()
self.widget_20.hide()
else:
self.widget_11.show()
self.widget_20.show()
except Exception as e:
e = traceback.format_exc()
self.loger.error(str(e))
def device_coord(self):
"""Get points according to the device"""
value = self.comboBox_device.currentText()
if value == 'myCobot 280 for Pi' or value == 'myCobot 280 for M5':
# yolov5 model file path
self.modelWeights = libraries_path + "/yolov5File/yolov5s.onnx"
# y-axis offset
self.pump_y = -55
# x-axis offset
self.pump_x = 15
self.move_angles = [
[0.61, 45.87, -92.37, -41.3, 2.02, 9.58], # init the point
[18.8, -7.91, -54.49, -23.02, -0.79, -14.76], # point to grab
]
self.move_coords = [
[132.2, -136.9, 200.8, -178.24, -3.72, -107.17], # D Sorting area
[238.8, -124.1, 204.3, -169.69, -5.52, -96.52], # C Sorting area
[115.8, 177.3, 210.6, 178.06, -0.92, -6.11], # A Sorting area
[-6.9, 173.2, 201.5, 179.93, 0.63, 33.83], # B Sorting area
]
self.new_move_coords_to_angles = [
[-24.87, -2.98, -92.46, 5.88, -3.07, -8.34], # D Sorting area
[-13.71, -52.11, -25.4, -4.57, -3.86, -7.73], # C Sorting area
[74.0, -18.1, -64.24, -9.84, -0.79, -9.49], # A Sorting area
[112.93, 3.16, -96.32, 0.87, 0.26, -9.75], # B Sorting area
]
self.home_coords = [145.0, -65.5, 280.1, 178.99, 7.67, -179.9]
elif value == 'myCobot 280 for JN':
# yolov5 model file path
self.modelWeights = libraries_path + "/yolov5File/yolov5s.onnx"
# y-axis offset
self.pump_y = -55
# x-axis offset
self.pump_x = 15
self.move_angles = [
[0.61, 45.87, -92.37, -41.3, 2.02, 9.58], # init the point
[18.63, 5.39, -83.49, -10.37, -0.08, -13.44], # point to grab
]
self.move_coords = [
[133.5, -149.5, 153.0, -178.91, -1.27, -112.78], # D Sorting area
[242.5, -143.1, 164.3, -172.38, -4.38, -100.28], # C Sorting area
[133.5, 168.0, 172.2, -175.89, -1.86, -13.65], # A Sorting area
[21.6, 176.3, 171.4, -178.53, -1.69, 21.75], # B Sorting area
]
self.home_coords = [145.0, -65.5, 280.1, 178.99, 7.67, -179.9]
elif value == 'myPalletizer 260 for M5' or value == 'myPalletizer 260 for Pi':
self.pump_y = -45
self.pump_x = -30
self.move_angles = [
[-22.0, 0, 0, 7.28], # point to grab
[17.4, -10.1, -87.27, 5.8], # point to grab
]
self.home_coords = [166.4, -21.8, 219, 0.96]
self.move_coords = [
[132.6, -155.6, 211.8, -20.9], # D Sorting area
[232.5, -134.1, 197.7, -45.26], # C Sorting area
[111.6, 159, 221.5, -120], # A Sorting area
[-15.9, 164.6, 217.5, -119.35], # B Sorting area
]
elif value == 'mechArm 270 for Pi' or value == 'mechArm 270 for M5':
self.pump_y = -55
self.pump_x = 15
self.move_angles = [
[-33.31, 2.02, -10.72, -0.08, 95, -54.84], # point to grab
[0, 0, 0, 0, 90, 0], # init the point
]
self.move_coords = [
[96.5, -101.9, 185.6, 155.25, 19.14, 75.88], # D
[180.9, -99.3, 184.6, 124.4, 30.9, 80.58], # C
[77.4, 122.1, 179.2, 151.66, 17.94, 178.24], # A
[2.2, 128.5, 171.6, 163.27, 10.58, -147.25] # B
]
self.home_coords = [81.8, -52.3, 186.7, 174.48, 4.08, 92.41]
elif value == 'ultraArm P340':
self.pump_y = -30
# x-axis offset
self.pump_x = -45
# 移动角度
self.move_angles = [
[25.55, 0.0, 15.24, 0],
[0.0, 14.32, 0.0, 0], # point to grab
]
# 移动坐标
self.move_coords = [
[141.53, 148.67, 43.73, 0], # D Sorting area
[248.52, 152.35, 53.45, 0], # C Sorting area
[269.02, -161.65, 51.42, 0], # A Sorting area
[146.8, -159.53, 50.44, 0], # B Sorting area
]
self.home_coords = [267.15, 0.0, 125.96]
def connect_mycobot(self):
"""Connect the arm"""
self.comboBox_port.setEnabled(False)
self.comboBox_buad.setEnabled(False)
self.comboBox_device.setEnabled(False)
device = self.comboBox_device.currentText()
port = self.comboBox_port.currentText()
baud = self.comboBox_buad.currentText()
baud = int(baud)
try:
if device == 'myPalletizer 260 for M5' or device == 'myPalletizer 260 for Pi':
self.myCobot = MyPalletizer260(port, baud, timeout=0.2)
elif device == 'ultraArm P340':
self.myCobot = ultraArm(port, baud, timeout=0.2)
self.stop_wait(0.1)
zero = threading.Thread(target=self.go_zero)
zero.start()
if self.language == 1:
self.prompts('Zero calibration is in progress, please wait patiently......')
else:
self.prompts('正在进行回零校正,请耐心等待......')
self.btn_status(False)
self.connect_btn.setEnabled(False)
elif device == 'mechArm 270 for Pi' or device == 'mechArm 270 for M5':
self.myCobot = MechArm270(port, baud, timeout=0.2)
else:
self.myCobot = MyCobot280(port, baud, timeout=0.2)
self.stop_wait(0.5)
self.loger.info("connection succeeded !")
if device != 'ultraArm P340':
self.btn_status(True)
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()
err_log = """\
\rConnection failed !!!
\r=================================================
{}
\r=================================================
""".format(
e
)
self.myCobot = None
self.comboBox_port.setEnabled(True)
self.comboBox_buad.setEnabled(True)
self.comboBox_device.setEnabled(True)
self.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.loger.error(err_log)
def disconnect_mycobot(self):
if not self.has_mycobot():
return
try:
del self.myCobot
self.myCobot = None
self.loger.info("Disconnected successfully !")
self.comboBox_port.setEnabled(True)
self.comboBox_buad.setEnabled(True)
self.comboBox_device.setEnabled(True)
if self.language == 1:
self.connect_btn.setText('CONNECT')
else:
self.connect_btn.setText('连接')
self.btn_color(self.connect_btn, 'green')
self.btn_color(self.discern_btn, 'blue')
self.btn_status(False)
self.auto_mode_status = False
self.discern_status = False
self.crawl_status = False
self.place_status = False
self.img_coord_status = False
self.current_coord_status = False
self.is_pick = False
except AttributeError:
self.loger.info("Not yet connected to mycobot!!!")
def connect_checked(self):
"""State toggle for the connect button"""
if self.language == 1:
txt = 'CONNECT'
else:
txt = '连接'
if self.connect_btn.text() == txt:
self.connect_mycobot()
else:
self.disconnect_mycobot()
def btn_status(self, status=False):
"""Some button state settings"""
btn_blue = [self.to_origin_btn, self.crawl_btn, self.place_btn]
btn_green = [self.auto_btn, self.current_coord_btn, self.image_coord_btn]
if status:
for b in btn_blue:
b.setEnabled(True) # clickable
b.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;")
for b in btn_green:
b.setEnabled(True)
b.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;")
else:
for b in btn_blue:
b.setEnabled(False) # not clickable
b.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;")
for b in btn_green:
b.setEnabled(False)
b.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;")
def open_camera(self):
"""Turn on the camera"""
try:
if self.language == 1:
self.prompts('Opening camera, please wait....')
else:
self.prompts('正在打开相机,请稍后....')
QApplication.processEvents()
self.camera_status = True
self.camera_edit.setEnabled(False)
flag = self.cap.open(int(self.camera_edit.text())) # Get the serial number of the camera to open
if not flag: # Flag indicates whether the camera is successfully opened
if self.language == 1:
self.prompts(
'The camera failed to open, please check whether the serial number is correct or the camera is connected.')
else:
self.prompts('相机打开失败,请检查序号是否正确或摄像头已连接.')
self.loger.error('Failed to open camera')
self.close_camera()
return
self.prompts_lab.clear()
self.yolov5_count = False
if self.language == 1:
self.add_img_btn.setText('Cut')
self.open_camera_btn.setText('Close')
else:
self.add_img_btn.setText('剪切')
self.open_camera_btn.setText('关闭')
self.btn_color(self.open_camera_btn, 'red')
except Exception as e:
e = traceback.format_exc()
self.loger.error('Unable to open camera' + str(e))
self.camera_status = False
self.camera_edit.setEnabled(True)
if self.language == 1:
self.open_camera_btn.setText('Open')
else:
self.open_camera_btn.setText('打开')
self.btn_color(self.open_camera_btn, 'green')
def close_camera(self):
"""turn off the camera"""
try:
self.camera_status = False
self.yolov5_is_not_pick = False
self.comboBox_function.setEnabled(True)
self.connect_btn.setEnabled(True)
self.is_yolov5_cut_btn_clicked = False
if self.has_mycobot():
self.auto_mode_status = True
self.auto_mode()
self.cap.release() # free video stream
self.camera_edit.setEnabled(True)
self.show_camera_lab.clear() # Clear the video display area
if self.language == 1:
self.open_camera_btn.setText('Open')
else:
self.open_camera_btn.setText('打开')
self.btn_color(self.open_camera_btn, 'green')
self._init_variable()
self.buad_choose()
self.prompts_lab.clear()
except Exception as e:
e = traceback.format_exc()
self.loger.error('camera off exception' + str(e))
def camera_checked(self):
"""Bind camera switch"""
if self.language == 1:
txt = 'Open'
else:
txt = '打开'
if self.open_camera_btn.text() == txt:
self.open_camera_func = 1
self.show_camera()
else:
if self.language == 1:
txt = 'Cut'
else:
txt = '剪切'
if self.add_img_btn.text() == txt:
if self.language == 1:
self.add_img_btn.setText('Add')
else:
self.add_img_btn.setText('添加')
self.close_camera()
def show_camera(self):
"""matching algorithm for identification"""
try:
if not self.camera_status: #
self.open_camera()
if not self.camera_status:
return
# Define Keypoints image storage/reading path
num = sum_x = sum_y = 0
is_release = False
while self.camera_status:
func = self.comboBox_function.currentText()
if func == 'Color recognition' or func == '颜色识别':
self.prompts_lab.clear()
# read camera
_, frame = self.cap.read()
# deal img
frame = self.transform_frame(frame)
QApplication.processEvents()
if self._init_ > 0:
self._init_ -= 1
if self.camera_status:
# The video color is converted back to RGB, so that it is the realistic color
show = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Convert the read video data into QImage format
showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0], show.shape[1] * 3,
QtGui.QImage.Format_RGB888)
# Display the QImage in the Label that displays the video
self.show_camera_lab.setPixmap(QtGui.QPixmap.fromImage(showImage))
continue
# calculate the parameters of camera clipping
QApplication.processEvents()
if self.init_num < 20:
if self.get_calculate_params(frame) is None:
if self.camera_status:
show = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0], show.shape[1] * 3,
QtGui.QImage.Format_RGB888)
self.show_camera_lab.setPixmap(
QtGui.QPixmap.fromImage(showImage))
continue
else:
x1, x2, y1, y2 = self.get_calculate_params(frame)
self.draw_marker(frame, x1, y1)
self.draw_marker(frame, x2, y2)
self.sum_x1 += x1
self.sum_x2 += x2
self.sum_y1 += y1
self.sum_y2 += y2
self.init_num += 1
continue
elif self.init_num == 20:
self.set_cut_params(
(self.sum_x1) / 20.0,
(self.sum_y1) / 20.0,
(self.sum_x2) / 20.0,
(self.sum_y2) / 20.0,
)
self.sum_x1 = self.sum_x2 = self.sum_y1 = self.sum_y2 = 0
self.init_num += 1
continue
# # calculate params of the coords between cube and mycobot
QApplication.processEvents()
if self.nparams < 10:
if self.get_calculate_params(frame) is None:
if self.camera_status:
show = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0], show.shape[1] * 3,
QtGui.QImage.Format_RGB888)
self.show_camera_lab.setPixmap(
QtGui.QPixmap.fromImage(showImage))
continue
else:
x1, x2, y1, y2 = self.get_calculate_params(frame)
self.draw_marker(frame, x1, y1)
self.draw_marker(frame, x2, y2)
self.sum_x1 += x1
self.sum_x2 += x2
self.sum_y1 += y1
self.sum_y2 += y2
self.nparams += 1
continue
elif self.nparams == 10:
self.nparams += 1
# calculate and set params of calculating real coord between cube and mycobot
self.set_params(
(self.sum_x1 + self.sum_x2) / 20.0,
(self.sum_y1 + self.sum_y2) / 20.0,
abs(self.sum_x1 - self.sum_x2) / 10.0 +
abs(self.sum_y1 - self.sum_y2) / 10.0
)
self.loger.info("Color recognition ok")
continue
# get detect result
QApplication.processEvents()
detect_result = None
if self.discern_status:
detect_result = self.color_detect(frame)
if detect_result is None:
if self.camera_status:
show = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0], show.shape[1] * 3,
QtGui.QImage.Format_RGB888)
self.show_camera_lab.setPixmap(QtGui.QPixmap.fromImage(showImage))
continue
else:
x, y = detect_result
# calculate real coord between cube and mycobot
self.real_x, self.real_y = self.get_position(x, y)
if self.num == 20:
if self.crawl_status or self.place_status:
self.decide_move(self.real_sx / 20.0, self.real_sy / 20.0, self.color)
self.num = self.real_sx = self.real_sy = 0
else:
self.num += 1
self.real_sy += self.real_y
self.real_sx += self.real_x
if self.camera_status:
show = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0], show.shape[1] * 3,
QtGui.QImage.Format_RGB888)
self.show_camera_lab.setPixmap(QtGui.QPixmap.fromImage(showImage))
elif func == 'Keypoints' or func == '特征点识别':
try:
res_queue = [[], [], [], []]
res_queue[0] = self.parse_folder('res/D')
res_queue[1] = self.parse_folder('res/C')
res_queue[2] = self.parse_folder('res/A')
res_queue[3] = self.parse_folder('res/B')
QApplication.processEvents()
self.prompts_lab.clear()
# read camera
_, frame = self.cap.read()
# deal img
frame = self.transform_frame(frame)
if self.init_num < 20:
if self.get_calculate_params(frame) is None:
if self.camera_status:
show = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0], show.shape[1] * 3,
QtGui.QImage.Format_RGB888)
self.show_camera_lab.setPixmap(
QtGui.QPixmap.fromImage(showImage))
continue
else:
x1, x2, y1, y2 = self.get_calculate_params(frame)
self.draw_marker(frame, x1, y1)
self.draw_marker(frame, x2, y2)
self.sum_x1 += x1
self.sum_x2 += x2
self.sum_y1 += y1
self.sum_y2 += y2
self.init_num += 1
continue
elif self.init_num == 20:
self.set_cut_params(
(self.sum_x1) / 20.0,
(self.sum_y1) / 20.0,
(self.sum_x2) / 20.0,
(self.sum_y2) / 20.0,
)
self.sum_x1 = self.sum_x2 = self.sum_y1 = self.sum_y2 = 0
self.init_num += 1
continue
# calculate params of the coords between cube and mycobot
if self.nparams < 10:
if self.get_calculate_params(frame) is None:
if self.camera_status:
show = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0], show.shape[1] * 3,
QtGui.QImage.Format_RGB888)
self.show_camera_lab.setPixmap(
QtGui.QPixmap.fromImage(showImage))
continue
else:
x1, x2, y1, y2 = self.get_calculate_params(frame)
self.draw_marker(frame, x1, y1)
self.draw_marker(frame, x2, y2)
self.sum_x1 += x1
self.sum_x2 += x2
self.sum_y1 += y1
self.sum_y2 += y2
self.nparams += 1
self.loger.info("Keypoints ok")
continue
elif self.nparams == 10:
self.nparams += 1
# calculate and set params of calculating real coord between cube and mycobot
self.set_params((self.sum_x1 + self.sum_x2) / 20.0,
(self.sum_y1 + self.sum_y2) / 20.0,
abs(self.sum_x1 - self.sum_x2) / 10.0 +
abs(self.sum_y1 - self.sum_y2) / 10.0)
self.loger.info("ok")
continue
# get detect result
detect_result = None
for i, v in enumerate(res_queue):
if self.discern_status:
detect_result = self.obj_detect(frame, v)
if detect_result is None:
if self.camera_status:
show = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0], show.shape[1] * 3,
QtGui.QImage.Format_RGB888)
self.show_camera_lab.setPixmap(
QtGui.QPixmap.fromImage(showImage))
continue
else:
x, y = detect_result
# calculate real coord between cube and mycobot
self.real_x, self.real_y = self.get_position(x, y)
if self.num == 5:
# self.color = i
# self.pub_marker(self.real_sx / 5.0 / 1000.0,
# self.real_sy / 5.0 / 1000.0)
if self.crawl_status:
self.decide_move(self.real_sx / 5.0, self.real_sy / 5.0,
self.color)
self.num = self.real_sx = self.real_sy = 0
else:
self.num += 1
self.real_sy += self.real_y
self.real_sx += self.real_x
if self.camera_status:
show = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0], show.shape[1] * 3,
QtGui.QImage.Format_RGB888)
self.show_camera_lab.setPixmap(QtGui.QPixmap.fromImage(showImage))
except Exception as e:
e = traceback.format_exc()
self.loger.error('Abnormal image recognition:' + str(e))
elif func == 'QR code recognition' or func == '二维码识别':
try:
QApplication.processEvents()
self.prompts_lab.clear()
success, img = self.cap.read()
if not success:
break
if self.discern_status:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
corners, ids, rejectImaPoint = cv2.aruco.detectMarkers(
gray, self.aruco_dict, parameters=self.aruco_params
)
if len(corners) > 0:
if ids is not None:
ret = cv2.aruco.estimatePoseSingleMarkers(
corners, 0.03, self.camera_matrix, self.dist_coeffs
)