-
Notifications
You must be signed in to change notification settings - Fork 0
/
CS3P_and_DPAC_run.py
4018 lines (3226 loc) · 170 KB
/
CS3P_and_DPAC_run.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
# -*- coding: utf-8 -*-
# @Author : Linsen Zhang
import math
import copy
import sys
import threading
from threading import Lock
import time
import CS3P_and_DPAC_codes.QT_UI as QT_UI
import pyautogui
from PyQt5.QtChart import QDateTimeAxis,QValueAxis,QSplineSeries,QChart,QChartView
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import json
import socket
from socket import SHUT_RDWR
import struct
import cv2
import os, psutil
from skimage import morphology, draw
import numpy as np
from scipy.optimize import leastsq
from PyQt5.QtOpenGL import QGLWidget
import vtk
from vtkmodules.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
import vtkmodules.vtkFiltersModeling
# import vmtk
import open3d as o3d
import operator
import datetime
from memory_profiler import profile
import CS3P_and_DPAC_codes.AstarSearch as a
import CS3P_and_DPAC_codes.AStar_2D as a_2d
# import AstarSearch_mp as a
import skeletor as sk
import trimesh
import multiprocessing
from multiprocessing import Process, Manager
from stl import mesh
import CS3P_and_DPAC_codes.WM_COPYDATA as WM_COPYDATA
import inspect
import ctypes
import CS3P_and_DPAC_codes.socket2robot as socket2robot
from vtk.util import numpy_support
import pyqtgraph as pg
import array
import random
mapDraw_flag = False
global_polydata = 0
import torch
import torch.nn as nn
import torch.optim as optim
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import OneHotEncoder
# import DWT
import openpyxl
import keyboard
import re
import CS3P_and_DPAC_codes.torque_period as torque_period
from scipy.interpolate import interp1d
from scipy.spatial.distance import euclidean
from scipy.spatial.distance import cdist
# model_path = "13_.STL"
# model_path = "vein_rot.STL"
# 动物
model_path = "CS3P_and_DPAC_codes/Model-data/238_smooth.stl"
# centerline file
centerline_path = "CS3P_and_DPAC_codes/Point-data/left_center.npy"
# Point file
point_file = "CS3P_and_DPAC_codes/Point-data/left.npy"
# device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class SKE_Node(object):
def __init__(self, index):
self.index = index
self.parent = None
class SKE_Plan(object):
def __init__(self, startindex, goalindex):
self.start = SKE_Node(startindex)
self.end = SKE_Node(goalindex)
self.nodeList = [self.start]
self.path_pointlist = []
def planning(self):
print("Begin centerline path planning.")
currentNode = self.start
flag = 0
n = 0
hash_table = []
h = hash(str(currentNode.index))
hash_table.append(h)
while 1:
flag = 0
currentNode = self.nodeList[n]
for i in range(len(main.skeleton_edge.tolist())):
if currentNode.index in main.skeleton_edge[i].tolist():
templist = main.skeleton_edge[i].tolist().copy()
templist.remove(currentNode.index)
new_node = copy.deepcopy(self.nodeList[0])
new_node.index = templist[0]
new_node.parent = self.nodeList.index(currentNode)
h = hash(str(new_node.index))
if h not in hash_table:
hash_table.append(h)
self.nodeList.append(new_node)
flag = 1
pass
if flag == 0:
print("Track not found!")
break
if new_node.index == self.end.index or currentNode.index == self.end.index:
print("Centerline path planning complete!")
break
n += 1
# Find the end point in the generated point set
path = []
end_index = 0
for i in range(len(self.nodeList)):
if self.nodeList[i].index == self.end.index:
end_index = i
# print("index:", i)
# Trajectory back
last_index = end_index
while self.nodeList[last_index].parent is not None:
node = self.nodeList[last_index]
path.append(node.index)
last_index = node.parent
if path[len(path) - 1] != self.end.index:
path.append(self.nodeList[last_index].index)
# Trajectory printing
path = path[::-1]
print("Centerline point trajectory:", path)
# Convert index in path to point
for i in range(len(path)):
self.path_pointlist.append(main.skeleton_point[path[i]].tolist())
if main.ske_display_actor != 0:
main.ren.RemoveActor(main.ske_display_actor)
# main.skeleton_display(self.path_pointlist, linecolor="lightgreen", linewidth=0.1)
main.skeleton_plan_point = self.path_pointlist.copy()
skeleton_point_save_array = np.array(main.skeleton_plan_point)
np.save("skeleton_point", skeleton_point_save_array)
return path
class interactor(vtk.vtkInteractorStyleTrackballCamera): # Interactive Classes Mouse Space Point Selection
def __init__(self, parent=None):
self.AddObserver("RightButtonPressEvent", self.RightButtonPressEvent)
self.AddObserver("MiddleButtonPressEvent", self.MiddleButtonPressEvent)
# self.AddObserver("LeftButtonPressEvent", self.LeftButtonPressEvent)
self.i = 1
self.controlpoints = {}
self.actor = []
self.modelFilePath = main.modelFilePath
self.firstpoint = []
self.lastpoint = []
self.firstpoint_index = 0
self.endpoint_index = 0
def MiddleButtonPressEvent(self, obj, event):
data = self.GetModelData(main.Reader)
clickPos = self.GetInteractor().GetEventPosition() # Get 2D image points
# Pick from this location
picker = self.GetInteractor().GetPicker() # Initialize the picker action
picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer()) # Self-defined rendering functions
value_list = []
for j in range(len(self.controlpoints)):
value_list.append(self.controlpoints[j + 1])
# If CellId = -1, nothing was picked
if value_list.count(data.GetPoint(picker.GetPointId())) == 0:
point_position = data.GetPoint(picker.GetPointId())
# Coordinates fitted to the entity
self.controlpoints[self.i] = point_position
list_point_position = []
list_point_position = list(point_position)
nearest_point = self.find_NearestPoint(list_point_position, main.skeleton_point)
# Create a sphere
sphereSource = vtk.vtkSphereSource()
sphereSource.SetCenter(nearest_point[0])
# sphereSource.SetRadius(0.2)
sphereSource.SetRadius(0.5)
print(nearest_point[0])
if nearest_point[0][1] > 200:
NDI_Point = vtk.vtkPoints()
NDI_Point.InsertNextPoint(nearest_point[0])
NDI_Point_polydata = vtk.vtkPolyData()
NDI_Point_polydata.SetPoints(NDI_Point)
NDI_vertex = vtk.vtkVertexGlyphFilter()
NDI_vertex.SetInputData(NDI_Point_polydata)
NDI_mapper = vtk.vtkPolyDataMapper()
NDI_mapper.SetInputConnection(NDI_vertex.GetOutputPort())
self.NDI_Pos_actor = vtk.vtkActor()
self.NDI_Pos_actor.SetMapper(NDI_mapper)
self.NDI_Pos_actor.GetProperty().SetPointSize(30) # Change the size of the point
colors = vtk.vtkNamedColors()
self.NDI_Pos_actor.GetProperty().SetColor(colors.GetColor3d("black")) # Dot color
self.NDI_Pos_actor.GetProperty().SetOpacity(1)
main.ren.AddActor(self.NDI_Pos_actor)
main.iren.Initialize()
def RightButtonPressEvent(self, obj, event):
data = self.GetModelData(main.Reader)
clickPos = self.GetInteractor().GetEventPosition() # Get 2D image points
# Pick from this location
picker = self.GetInteractor().GetPicker() # Initialize the picker action
picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer()) # Self-defined rendering functions
value_list = []
for j in range(len(self.controlpoints)):
value_list.append(self.controlpoints[j + 1])
# If CellId = -1, nothing was picked
if value_list.count(data.GetPoint(picker.GetPointId())) == 0:
point_position = data.GetPoint(picker.GetPointId())
# Coordinates fitted to the entity
self.controlpoints[self.i] = point_position
list_point_position = []
list_point_position = list(point_position)
nearest_point = self.find_NearestPoint(list_point_position, main.skeleton_point)
# Create a sphere
sphereSource = vtk.vtkSphereSource()
sphereSource.SetCenter(nearest_point[0])
# sphereSource.SetRadius(0.2)
sphereSource.SetRadius(0.5)
print(nearest_point[0])
# Create a mapper and actor
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(sphereSource.GetOutputPort())
self.actor.append(vtk.vtkActor())
self.actor[self.i - 1].SetMapper(mapper)
self.actor[self.i - 1].GetProperty().SetColor(0, 0, 0)
self.GetDefaultRenderer().AddActor(self.actor[self.i - 1])
self.i += 1
self.OnRightButtonDown()
# print(main.skeleton_edge)
try: # Avoid selection points that no longer report errors on the model
if len(self.firstpoint) != 0 and nearest_point[0].tolist() != self.firstpoint:
main.ren.RemoveActor(main.text_2d_actor)
self.lastpoint = nearest_point[0].tolist()
self.endpoint_index = main.skeleton_point.tolist().index(self.lastpoint)
print("The End:", [round(x, 2) for x in nearest_point[0]], end=" ")
print("Terminal serial number:", self.endpoint_index)
main.path_endpoint = [nearest_point[0][0], nearest_point[0][1], nearest_point[0][2]] # Global path planning endpoint setting
main.actor_vascular.GetProperty().SetColor(1, 0, 0) # Color switching when selecting points Arteries Veins
main.iren.Initialize()
skeleton_plan = SKE_Plan(self.firstpoint_index, self.endpoint_index)
skeleton_plan.planning()
else:
self.firstpoint = nearest_point[0].tolist()
self.firstpoint_index = main.skeleton_point.tolist().index(self.firstpoint)
for i in range(len(nearest_point[0])):
# Starting coordinates rounded Reduced calculations
nearest_point[0][i] = round(nearest_point[0][i])
pass
print("Starting point:", nearest_point[0][0], nearest_point[0][1], nearest_point[0][2], end=" ")
print("Starting point serial number:", self.firstpoint_index)
main.path_startpoint = [nearest_point[0][0], nearest_point[0][1], nearest_point[0][2]] # Global route planning starting point setup
main.text_2d_actor.SetInput("Select EndPoint")
main.ren.AddActor(main.text_2d_actor)
except:
pass
return
def GetModelData(self, Reader):
data = Reader.GetOutput()
# print("nodes number:", data.GetNumberOfPoints())
if data.GetNumberOfPoints() == 0:
raise ValueError("No point data could be loaded from " + self.modelFilePath)
return None
return data
def points_distance(self, point1, point2): # Calculate the distance between two points Input: two points [list] Return: distance
return math.sqrt(math.pow(point1[0]-point2[0], 2)+math.pow(point1[1]-point2[1], 2)+math.pow(point1[2]-point2[2], 2))
def find_NearestPoint(self, test_point, pointlist):
shortest_distance = 99999
shortest_point = []
test_point = list(test_point)
pointlist = list(pointlist)
for i in range(len(pointlist)):
res = self.points_distance(test_point, pointlist[i])
if res < shortest_distance:
shortest_distance = res
shortest_point.clear()
shortest_point.append(pointlist[i])
return shortest_point
class MainWin(QtWidgets.QMainWindow):
# Create the main form
def __init__(self, parent=None):
super(MainWin, self).__init__(parent)
self.x0 = 0
self.x1 = 0
self.json_list = []
self.tcp_socket = 0
self.connect_flag = False
cols, rows = 512, 512
self.bin_img = [[0 for col in range(cols)] for row in range(rows)]
self.ske_map = []
self.mapDraw_flag = False
self.roadDraw_flag = False
self.dividepoint_list = [0, 0]
self.divide_flag = False
self.sorted_ske_map = []
self.handshake = [0xAA, 0xAA, 0x01, 0x00, 0x00, 0x00, 0x25, 0xf6, 0x01, 0x00, 0x32, 0x00, 0x00, 0x01, 0x02, 0x52, 0x55, 0x55]
self.operate = [0xAA, 0xAA, 0x01, 0x00, 0x00, 0x00, 0xA8, 0xC3, 0x00, 0x00, 0x41, 0x00, 0x00, 0x01, 0x01, 0xAF, 0x55, 0x55]
self.operate_slave = [0xAA, 0xAA, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x41, 0x00, 0x00, 0x01, 0x01, 0x44, 0x55, 0x55]
self.handshake_flag = False
self.connectSuccess_flag = False
self.operateTimer = 0
self.operateCount = 10
self.tcp_client = 0
self.CtrlFlag = 0
self.BeginFlag = 0
self.RecCheckSum = 0
self.FRAME_HEAD = 0xAA
self.FRAME_TAIL = 0x55
self.FRAME_CTRL = 0xA5
self.MaxPackageSize = 40
self.LastByte = 0
self.RevOffset = 0
self.RevOffset = 0
self.g_LostPackage_Net = 0
self.PROTOCOL_TRUE = 1
self.PROTOCOL_FALSE = 0
self.BeginFlag = self.PROTOCOL_FALSE
self.g_ValidDataCount_Net = 0
self.g_RxBuf_Net = [0 for x in range(0,self.MaxPackageSize)]
self.canMessage_StdId = 0
self.canMessage_RTR = 0
self.canMessage_DLC = 0
self.canMessage_Data = []
self.g_tMaster_ActualAdvCountOfGw1 = 0
self.g_tMaster_ActualAdvSpeedOfGw1 = 0
self.g_tMaster_ActualRotCountOfGw1 = 0
self.g_tMaster_ActualRotSpeedOfGw1 = 0
self.g_tMaster_ActualAdvCountOfCath = 0
self.g_tMaster_ActualAdvSpeedOfCath = 0
self.g_tMaster_ActualRotCountOfCath = 0
self.g_tMaster_ActualRotSpeedOfCath = 0
self.recPosNow = 0
self.recVelNow = 0
self.recCurrent = 0
self.recTorque = 0
self.centralwidget = 0
self.vtkWidget = 0
self.ren = 0
self.iren = 0
self.vascular_opacityRate = 100
self.first_3D = False
self.skeImagePath = "/PNG/label.png"
self.pcdFilePath = "3D.pcd"
self.modelFilePath = model_path
self.points = []
self.face = []
self.edge = []
self.normal_vector = []
self.init_touch_list = []
self.touch_list = []
self.path_startpoint = [8, 0, 63]
self.path_endpoint = [-0.64, 277.47, 83.79]
self.Reader = 0
self.vascular_polydata = 0
self.dyn_line_point = 0
self.dyn_lineSource = 0
self.dyn_actor_line = 0
self.dyn_num = 0
self.pointlist = 0
self.path_display_flag = False
self.path_display_actor = 0
self.skeleton_point = []
self.skeleton_edge = []
self.skeleton_display_flag = []
self.ske_display_actor = 0
self.skeleton_plan_point = []
self.actor_vascular = 0
self.text_3d_actor = 0
self.text_3d_textSource = 0
self.text_2d_actor = 0
self.text_2d_textSource = 0
self.A_star_pathdata = []
self.m = Manager()
# 0 1 2 3 4 5 6 7 8 9
# pathdata, openlist, hashset, col_hashset, guidewire blind localization displacement run flag, guidewire blind localization angle run flag, points in Openlist that meet constraints, segmented point list, clustered point set list, Open that meets requirements, [bending energy, spherical end collision list]
self.process_data = self.m.list([0, [], 0, 0, 0, 0, [], [], [], []])
self.Openlist = []
self.hashset = set()
self.col_hashset = set()
# 2D盲定位变量
self.process_data_2d = self.m.list([0, [], 0, 0, 0, 0, [], [], [], []])
self.Openlist_2d = []
self.hashset_2d = set()
self.col_hashset_2d = set()
self.guidewire_displacement_2d = 0
self.guidewire_angle_2d = 0
self.guidewire_control_msg = [] # Format: [absolute displacement, rotation]
self.catheter_control_msg = [] # Format: [absolute displacement, rotation]
self.frame_guidewire_control_msg = 0
self.frame_catheter_control_msg = 0
self.guidewire_zero_position = 0 # [Guide wire] 0 position displacement
self.catheter_zero_position = 0 # [Catheter] 0 position displacement
self.guidewire_current_position = 0 # [Guide Wire] Current Absolute Position
self.guidewire_current_angle = 0 # [Guide Wire] Current Absolute Angle
self.catheter_current_position = 0 # [Conduit] Current absolute position
self.catheter_current_angle = 0 # [Ducting] Current absolute angle
self.guidewire_position_factor = 1.0 # [Wire Guide] Displacement vs. Model Scale Relationships
self.guidewire_angle_factor = 1.0 # [Wire guide] Angle value and actual rotation angle ratio relationship
self.catheter_position_factor = 1.0 # [Conduit] Displacement and Model Scale Relationships
self.catheter_angle_factor = 1.0 # [Conduit] Angle value proportional to the actual rotation angle
self.flag_Blind_Switch = 0
self.blind_timer = 0
self.Open_point_list = []
self.current_display_pointlist = []
self.blindpoint_actor_list = []
self.flag_blindpoint_actor = False
self.thread_lock = Lock()
self.advance_test = 0
self.twist_test = 0
self.blind_process = 0
self.NDI_listern_thread = 0
self.NDI_Read_timer = 0
self.NDI_data = [""]
self.NDI_data_old = [""]
self.NDI_data_processed = []
self.NDI_Pos_Record = []
self.NDI_Pos_actor = 0
self.NDI_Pos_ICP = 0
self.Transform_matrix = 0
self.x_offset = -27
self.y_offset = -1300
self.z_offset = 53
self.robot_dis = 0
self.robot_ang = 0
# self.adv_rate = 34.1426 / 4096
self.adv_rate = 1 / 113.6534
self.rot_rate = 22.566
self.Node_save = []
self.blind_current_step = 0
self.blindpoint_actor_list1 = []
self.Node_list = []
self.robot_dis_1 = 0
self.auto_del_flag = 0
self.voice_play = 0
self.cam_point = []
# 目标位置 target_dis
self.target_dis = 550
# 力矩检测标志位
self.torque_flag = 0
self.list_torque = []
self.torque_plot = 0
self.torque_curve = 0
self.torque_pen = 0
# Neural network inputs [Displacement, velocity, torque]
self.NN_input = []
self.force_state = 0 # Tip-top collision state
self.ske_dis = []
self.branch_point = []
self.ske_path_point = []
self.block_pos = 0
self.ske_point_num = 0
self.workbook = 0
self.sheet = 0
self.NN_input_save = []
self.keyboard_thread = 0
self.torque_label_input = 0
self.list_res_dis = []
self.torqueinit_flag = 0
self.torqueinit_data = [[], []]
self.avg_list = []
self.phase_bias = 0
self.torque_res_dis = 0
self.torque_noise = 0
self.current_avg_pointset = []
self.sector_avg_branch_list = []
self.avg_point_list = []
self.cath_comp_path_actor_list = []
self.last_DWT_Dis = 0
self.cath_comp_flag = 0
self.data_record = []
self.data_record1 = []
self.new_ren = 0
self.new_iren= 0
self.multpoint_dis_flag = 1
self.cur_instr_dis = 0
self.vtkWidget2 = 0
self.swap_widget_flag = 0
self.video_capture = 0
self.prev_frame = None
self.current_tor = 0
self.torque_delay = 0
self.force_2D_actor = 0
self.current_light = 0
self.current_camera_pos = [0, 0, 0]
self.current_camera_focus = [0, 0, 0]
self.rot_dir = 0
def closeEvent(self, event):
# Window exit handlers
try:
# Delete individual processes
if self.blind_timer != 0:
self.blind_timer.cancel()
if self.NDI_Read_timer != 0:
self.NDI_Read_timer.cancel()
if self.blind_process != 0:
self.blind_process.terminate()
# Stop the keyboard listener thread
self.keyboard_thread.stop()
# Wait for the keyboard listener thread to finish
self.keyboard_thread.join()
print("\033[1;30;41m※※※The system is down.※※※\033[0m")
sys.stdout = sys.__stdout__
super().closeEvent(event)
# Force a shutdown Terminate thread processes that can't be shut down above
os._exit(0)
except:
print("\033[1;30;41mSystem Shutdown Failed!\033[0m")
def init_video_display(self):
self.video_capture = cv2.VideoCapture(0) # Turn on the camera
if not self.video_capture.isOpened():
print("Unable to open the camera")
# sys.exit(1)
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_frame)
self.timer.start(50)
# Create a QLabel to display the image
self.video_display_label = QLabel(self)
ui.verticalLayout_7.addWidget(self.video_display_label)
def update_frame(self):
ret, frame = self.video_capture.read()
if ret:
if self.prev_frame is None:
self.prev_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
else:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
flow = cv2.calcOpticalFlowFarneback(self.prev_frame, gray, None, 0.5, 3, 15, 3, 5, 1.2, 0)
magnitude, _ = cv2.cartToPolar(flow[..., 0], flow[..., 1])
magnitude = cv2.normalize(magnitude, None, 0, 255, cv2.NORM_MINMAX)
magnitude = magnitude.astype(np.uint8)
# Raise the threshold for recognition
threshold = 150
# Calculate a binary image of the region of change
change_area = cv2.threshold(magnitude, threshold, 255, cv2.THRESH_BINARY)[1]
# Finding the contours of areas of change
contours, _ = cv2.findContours(change_area, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Fill the change area with red on the original image
result_frame = frame.copy()
red_color = (0, 255, 255) # The order is BGR not RGB!
for contour in contours:
cv2.fillPoly(result_frame, [contour], red_color) # Fill with red
image = cv2.cvtColor(result_frame, cv2.COLOR_BGR2RGB)
h, w, c = image.shape
q_image = QImage(image.data, w, h, w * c, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(q_image)
# Display images on QLabel
self.video_display_label.setPixmap(pixmap)
self.prev_frame = gray
def paintEvent(self, event): # Drawing program All drawing operations need to be done here.
painter = QPainter(self)
painter.setPen(QPen(Qt.red, 1, Qt.DashLine))
if self.mapDraw_flag is True:
x = 0
# Connecting the dots
while x < len(self.json_list):
if x > 0:
painter.drawLine(int(self.json_list[x - 1][0]), int(self.json_list[x - 1][1]),
int(self.json_list[x][0]), int(self.json_list[x][1]))
x = x + 1
elif x == 0:
x = x + 1
# Sealing
painter.drawLine(int(self.json_list[0][0]), int(self.json_list[0][1]),
int(self.json_list[len(self.json_list) - 1][0]), int(self.json_list[len(self.json_list) - 1][1]))
painter.setPen(QPen(Qt.yellow, 2, Qt.SolidLine))
painter.drawLine(int(self.json_list[0][0]),int(self.json_list[0][1])-5,int(self.json_list[len(self.json_list) - 1][0]),int(self.json_list[len(self.json_list) - 1][1])-5)
self.update()
else:
self.update()
if self.roadDraw_flag is True:
if self.divide_flag is False:
self.Line_sort()
self.divide_flag = True # Calculate duplicate points and then stop counting
painter.setPen(QPen(Qt.white, 1, Qt.DashLine))
for x in range(len(self.sorted_ske_map)):
if x < 50:
painter.setPen(QPen(QColor(255, 255, 255), 1, Qt.DashLine))
elif x < 100:
painter.setPen(QPen(QColor(233, 233, 233), 1, Qt.DashLine))
elif x < 150:
painter.setPen(QPen(QColor(200, 200, 200), 1, Qt.DashLine))
elif x < 200:
painter.setPen(QPen(QColor(160, 160, 160), 1, Qt.DashLine))
elif x < 250:
painter.setPen(QPen(QColor(120, 120, 120), 1, Qt.DashLine))
elif x < 300:
painter.setPen(QPen(QColor(137, 102, 138), 1, Qt.DashLine))
elif x < 350:
painter.setPen(QPen(QColor(90, 83, 157), 1, Qt.DashLine))
elif x < 400:
painter.setPen(QPen(QColor(64, 154, 176), 1, Qt.DashLine))
elif x < 450:
painter.setPen(QPen(QColor(206, 210, 30), 1, Qt.DashLine))
elif x < 500:
painter.setPen(QPen(QColor(224, 125, 16), 1, Qt.DashLine))
elif x < 550:
painter.setPen(QPen(QColor(240, 0, 0), 1, Qt.DashLine))
painter.drawPoint(self.sorted_ske_map[x][0], self.sorted_ske_map[x][1]) # Drawing a road map The coordinate system is reversed
self.update()
else:
self.update()
# 2d blind positioning endpoint display program
if len(self.process_data_2d[6])!= 0:
painter.setPen(QPen(QColor(255, 0, 0), 2, Qt.DashLine))
for i in range(len(self.process_data_2d[6])):
try:
painter.drawPoint(round(self.process_data_2d[6][i][0][0]), round(self.process_data_2d[6][i][0][1]))
except:
painter.drawPoint(round(self.process_data_2d[6][i][0]), round(self.process_data_2d[6][i][1]))
self.update()
def Line_sort(self): # Sorting program for line segments after erosion
# Find the start point, (the point furthest down) the point with the largest Y
startpoint_Y = 250
startpoint_X = 0
lastpoint_X = 0
lastpoint_Y = 0
search_range = 1
# Find the initial point, the bottom point #
for x in range(len(self.ske_map)):
if self.ske_map[x][0] > startpoint_Y:
startpoint_Y = self.ske_map[x][0]
startpoint_X = self.ske_map[x][1]
# print("startpoint_Y=", startpoint_Y, "startpoint_X=", startpoint_X)
# Sorting from the initial point
self.sorted_ske_map.clear()
self.sorted_ske_map.append([startpoint_X,startpoint_Y])
lastpoint_X = startpoint_X
lastpoint_Y = startpoint_Y
for x in range(len(self.ske_map)):
for y in range(len(self.ske_map)):
if abs(self.ske_map[y][0] - startpoint_Y) <= search_range \
and abs(self.ske_map[y][1] - startpoint_X) <= search_range \
and (self.ske_map[y][0] != startpoint_Y or self.ske_map[y][1] != startpoint_X) \
and (self.ske_map[y][0] != lastpoint_Y or self.ske_map[y][1] != lastpoint_X):
self.sorted_ske_map.append([self.ske_map[y][1],self.ske_map[y][0]])
lastpoint_X = startpoint_X
lastpoint_Y = startpoint_Y
startpoint_Y = self.ske_map[y][0]
startpoint_X = self.ske_map[y][1]
# print(self.sorted_ske_map) # Sorted lines
def mousePressEvent(self, event): # Read the mouse point
self.flag = True
self.x0 = event.x()
self.y0 = event.y()
if self.x0 <= 512 and self.y0 <= 512:
print("select point:", self.x0, self.y0)
else:
# print("Not DSA Area")
pass
self.point_calibration = True
self.update()
def tcp_connect(self): # TCP connection program
try:
print("TCP Connecting")
ui.pushButton_5.setEnabled(False)
ui.pushButton_6.setEnabled(True)
# IP address
server_ip = ui.lineEdit.text()
# Port number
server_port = ui.lineEdit_2.text()
# Create sockets
self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Set up port multiplexing so that ports are released immediately after program exit
self.tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
# Server-side connection program
# Binding ports
self.tcp_socket.bind(("", int(server_port)))
# Set up the listener
self.tcp_socket.listen(128)
self.connect_flag = True
self.tcp_client, tcp_client_address = self.tcp_socket.accept()
# Create multi-threaded objects
tcp_server_thread = threading.Thread(target=self.tcp_receive_server, args = (self.tcp_client,tcp_client_address)).start()
print("TCP_Connect Success ")
main.status.showMessage('TCP_Connect Success', 1000)
except Exception as e:
print(e)
print("TCP Connect Failed")
main.status.showMessage('TCP Connect Failed', 1000)
def tcp_disconnect(self): # TCP disconnection procedure
try:
self.tcp_socket.close()
self.connect_flag = False
print("TCP Disconnect")
main.status.showMessage('TCP Disconnect', 1000)
ui.pushButton_5.setEnabled(True)
ui.pushButton_6.setEnabled(False)
except Exception as e:
print(e)
print("TCP Disconnect Failed")
main.status.showMessage('TCP Disconnect Failed', 1000)
def tcp_send(self, send_buffer): # TCP sender program
try:
print("data length:",len(send_buffer),',',end='')
data = struct.pack("%dB" % (len(send_buffer)), *send_buffer)
print("Data:", data)
# Client mode
self.tcp_socket.send(data)
# Server-side model
self.tcp_client.send(data)
#print("Data is sent")
#main.status.showMessage('Data is Sent', 1000)
except:
main.status.showMessage('TCP Send Failed', 1000)
def tcp_receive_server(self, client, clientaddress): # TCP receiver program ( runs in a separate thread ) server side
try:
print("TCP Rec_Thread Created")
print("Robot_Address:{}".format(clientaddress))
recBuffer_size = 1024
while self.connect_flag:
data = client.recv(recBuffer_size)
print('new data length:', len(data), ',', 'data:', end="")
for x in range(len(data)):
print(hex(data[x]), ' ', end="")
print() # Row line feeds
# if list(data) == self.handshake: # Receive a handshake from the slave
if data[10] == 0x32 and data[11] == 0x00 and data[12] == 0x00 and data[13] == 0x01: # Receive a handshake from the slave
self.handshake_flag = True
self.operateTimer = threading.Timer(0.5, self.cycleSend_operate)
self.operateTimer.start()
print("OPERATE SEND")
# Successful handshake.
# elif list(data) == self.operate_slave: # Receive an operation from the slave
elif data[10] == 0x42 and data[11] == 0x00 and data[12] == 0x00 and data[13] == 0x01: # Receive an operation from the slave
self.handshake_flag = False
self.connectSuccess_flag = 1 # Handshake success sign
ui.pushButton_5.setText("HS Succuess")
print("Successful handshake.")
if len(data)!= 0:
for index in range(len(data)):
if self.ParseByteFromNet(data[index]) == self.PROTOCOL_TRUE:
self.canMessage_StdId = self.g_RxBuf_Net[8] + (self.g_RxBuf_Net[9] << 8)
self.canMessage_RTR = self.g_RxBuf_Net[10]
self.canMessage_DLC = self.g_RxBuf_Net[11]
for can_index in range(self.canMessage_DLC):
self.canMessage_Data[can_index] = self.g_RxBuf_Net[can_index+12]
self.parseSlaveMsg() # Slave sensor data parsing
if not data:
self.connect_flag = 0
print("Slave disconnected")
self.client.close()
# print("TCP Connect ERROR")
# main.status.showMessage('TCP Connect ERROR', 1000)
break
except Exception as e:
print(e)
print("TCP_Receive Failed")
main.status.showMessage('TCP_Receive Failed', 1000)
def tcp_receive(self): # TCP receiver program ( runs in a separate thread ) Clients
try:
print("TCP Rec_Thread Created")
recBuffer_size = 1024
while self.connect_flag:
data = self.tcp_socket.recv(recBuffer_size)
print('new data length:', len(data), ',', 'data:', end="")
for x in range(len(data)):
print(hex(data[x]), ' ', end="")
print()
if list(data) == self.handshake: # Receive a handshake from the slave
self.handshake_flag = True
self.operateTimer = threading.Timer(0.5, self.cycleSend_operate)
self.operateTimer.start()
# A successful handshake
elif list(data) == self.operate_slave: # Receive an operation from the slave
self.handshake_flag = False
self.connectSuccess_flag = 1 # Handshake success sign
ui.pushButton_5.setText("HS Succuess")
if len(data)!= 0:
for index in range(len(data)):
if self.ParseByteFromNet(data[index]) == self.PROTOCOL_TRUE:
self.canMessage_StdId = self.g_RxBuf_Net[8] + (self.g_RxBuf_Net[9] << 8)
self.canMessage_RTR = self.g_RxBuf_Net[10]
self.canMessage_DLC = self.g_RxBuf_Net[11]
for can_index in range(self.canMessage_DLC):
self.canMessage_Data[can_index] = self.g_RxBuf_Net[can_index+12]
self.parseSlaveMsg() # Slave sensor data parsing
if not data:
self.connect_flag = 0
# print("TCP Connect ERROR")
# main.status.showMessage('TCP Connect ERROR', 1000)
break
except:
print("TCP_Receive Failed")
main.status.showMessage('TCP_Receive Failed', 1000)
def parseSlaveMsg(self): # Slave sensor feedback parsing program
if self.canMessage_StdId == 0x62: # Position and velocity feedback S2M_RPL_PosAndVel
if self.canMessage_RTR == 0x01: # Guide wire delivery
self.g_tMaster_ActualAdvCountOfGw1 = (self.canMessage_Data[0]) + (self.canMessage_Data[1] << 8) \
+ (self.canMessage_Data[2] << 16) + (self.canMessage_Data[3] << 24)
self.g_tMaster_ActualAdvSpeedOfGw1 = (self.canMessage_Data[4]) + (self.canMessage_Data[5] << 8) \
+ (self.canMessage_Data[6] << 16) + (self.canMessage_Data[7] << 24)
self.guidewire_current_position = self.g_tMaster_ActualAdvCountOfGw1 # [Guide Wire] Current Absolute Displacement
relative_position = self.guidewire_current_position - self.guidewire_zero_position # Relative displacement
if relative_position >= 0: # Greater than or equal to 0
self.guidewire_control_msg.append([relative_position * self.guidewire_position_factor, 0]) # Relative displacement is all positive.
else:
pass
# self.guidewire_control_msg.append([0, 0]) # [Guide Wire] Relative Displacement
print("[Guidewire delivery]__ Absolute displacement:{} ".format(self.guidewire_current_position), "__ Speed:{}".format(self.g_tMaster_ActualAdvSpeedOfGw1))
elif self.canMessage_RTR == 0x02: # Guide wire rotation
self.g_tMaster_ActualRotCountOfGw1 = (self.canMessage_Data[0]) + (self.canMessage_Data[1] << 8) \
+ (self.canMessage_Data[2] << 16) + (self.canMessage_Data[3] << 24)
self.g_tMaster_ActualRotSpeedOfGw1 = (self.canMessage_Data[4]) + (self.canMessage_Data[5] << 8) \
+ (self.canMessage_Data[6] << 16) + (self.canMessage_Data[7] << 24)
if self.guidewire_current_angle != 0:
relative_angle = self.g_tMaster_ActualRotCountOfGw1 - self.guidewire_current_angle # [Guide Wire] Angle change value has a positive reading.
else: # Getting the angle value for the first time
relative_angle = 0
self.guidewire_current_angle = self.g_tMaster_ActualRotCountOfGw1 # [Guide Wire] Current Absolute Angle
self.guidewire_control_msg.append([0, relative_angle * self.guidewire_angle_factor ]) # [Guide Wire] Current Relative Angle
print("[Guidewire rotation]___ Absolute angle:{} ".format(self.guidewire_current_angle), "__Speed:{}".format(self.g_tMaster_ActualRotSpeedOfGw1))
elif self.canMessage_RTR == 0x03: # catheter push
self.g_tMaster_ActualAdvCountOfCath = (self.canMessage_Data[0]) + (self.canMessage_Data[1] << 8) \