forked from atelier-ritz/CoilSystemPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvision.py
More file actions
306 lines (226 loc) · 11.2 KB
/
vision.py
File metadata and controls
306 lines (226 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
"""
=============================================================================
vision.py
----------------------------------------------------------------------------
Version
1.1.0 2018/08/04 Added snapshot feature.
1.0.0 2018/06/16 Added video writing feature.
0.0.1 2018/02/05 Initial commit
----------------------------------------------------------------------------
[GitHub] : https://github.com/atelier-ritz
=============================================================================
"""
import cv2
import sys
import re
import time
from PyQt5.QtCore import QThread, pyqtSignal
from pydc1394 import Camera
import filterlib
import drawing
import objectDetection
from objectDetection import Agent
from pypylon import pylon
import numpy as np
import traceback
import datetime
#=============================================================================================
# Mouse callback Functions
#=============================================================================================
def showClickedCoordinate(event,x,y,flags,param):
# global mouseX,mouseY
if event == cv2.EVENT_LBUTTONDOWN:
# mouseX,mouseY = x,y
print('Clicked position x: {} y: {}'.format(x,y))
#=============================================================================================
# Camera Thread to handle Basler Pylon Camera in a separate thread
#=============================================================================================
class CameraThread(QThread):
frame_ready = pyqtSignal(object)
def __init__(self, camera_index):
super(CameraThread, self).__init__()
self.running = False
self.camera = None
self.converter = None
self.camera_index = camera_index
def run(self):
try:
devices = pylon.TlFactory.GetInstance().EnumerateDevices()
if len(devices) <= self.camera_index:
raise Exception(f"❌ No camera found at index {self.camera_index}")
selected_device = devices[self.camera_index]
print(f"✅ Opening camera: {selected_device.GetModelName()}")
self.camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateDevice(selected_device))
self.camera.Open()
self.camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)
self.converter = pylon.ImageFormatConverter()
self.converter.OutputPixelFormat = pylon.PixelType_BGR8packed
self.converter.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned
print(f"✅ Camera {self.camera_index} started grabbing.")
self.running = True
while self.running and self.camera.IsGrabbing():
grabResult = self.camera.RetrieveResult(5000, pylon.TimeoutHandling_ThrowException)
if not grabResult.IsValid() or not grabResult.GrabSucceeded():
# print(f"⚠️ Camera {self.camera_index}: No valid frame received.")
grabResult.Release()
continue
image = self.converter.Convert(grabResult)
frame = image.GetArray()
# print(f"📷 Camera {self.camera_index} frame shape: {frame.shape}")
if self.frame_ready:
# print(f"✅ Emitting frame from Camera {self.camera_index}") # ✅ 确保触发
self.frame_ready.emit(frame)
grabResult.Release()
except Exception as e:
print(f"❌ Camera {self.camera_index} error: {e}")
finally:
self.stop()
print(f"✅ Camera {self.camera_index} thread ended.")
def stop(self):
self.running = False
if self.camera and self.camera.IsGrabbing():
self.camera.StopGrabbing()
if self.camera:
self.camera.Close()
self.quit()
self.wait()
print(f"✅ Camera {self.camera_index} stopped successfully")
class Vision(object):
def __init__(self,index,type, guid=0000000000000000,buffersize=10):
self._id = index
self._type = type
self._guid = guid
self._isUpdating = True
self._isFilterBypassed = True
self._isObjectDetectionEnabled = False
self._isSnapshotEnabled = False
self._detectionAlgorithm = ''
self.camera_thread = None
self.filterRouting = [] # data structure: {"filterName", "args"}, defined in the GUI text editor
# self._camera_index = camera_index
# instances of Agent class. You can define an array if you have multiple agents.
# Pass them to *processObjectDetection()*
self.agent1 = Agent()
self.agent2 = Agent()
# drawings
self.drawingRouting = [] # data structure: {"drawingName", "args"}, defined in Subthread
# video writing
self._isVideoWritingEnabled = False
self.videoWriter = None
def process_frame(self, frame):
if not self._isFilterBypassed and self.filterRouting:
frame = self.processFilters(frame.copy())
if self._isObjectDetectionEnabled:
frame = self.processObjectDetection(frame, frame)
if self.isDrawingEnabled():
frame = self.processDrawings(frame)
if self.isSnapshotEnabled():
snapshot_frame = frame.copy()
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"snapshot_{timestamp}.png"
cv2.imwrite(filename, filterlib.color(snapshot_frame))
print(f"✅ snapshot: {filename}")
self.setStateSnapshotEnabled(False)
if self.isVideoWritingEnabled() and self.videoWriter is not None:
self.videoWriter.write(filterlib.color(frame))
return frame
def updateFrame(self):
pass
#==============================================================================================
# obtain instance attributes
#==============================================================================================
def windowName(self):
return 'CamID:{} (Click to print coordinate)'.format(self._id)
def isFireWire(self):
return self._type.lower() == 'firewire'
def isUpdating(self):
return self._isUpdating
def isFilterBypassed(self):
return self._isFilterBypassed
def isObjectDetectionEnabled(self):
return self._isObjectDetectionEnabled
def isDrawingEnabled(self):
return not self.drawingRouting == []
def isSnapshotEnabled(self):
return self._isSnapshotEnabled
def isVideoWritingEnabled(self):
return self._isVideoWritingEnabled
#==============================================================================================
# set instance attributes
#==============================================================================================
def setStateUpdate(self,state):
self._isUpdating = state
def setStateFiltersBypassed(self,state):
self._isFilterBypassed = state
def setStateObjectDetection(self,state,algorithm):
self._isObjectDetectionEnabled = state
self._detectionAlgorithm = algorithm
def setVideoWritingEnabled(self,state):
self._isVideoWritingEnabled = state
def setStateSnapshotEnabled(self,state):
self._isSnapshotEnabled = state
# print(f"⚡ Snapshot Enabled: {state}")
#==============================================================================================
# Video recording
#==============================================================================================
def createVideoWriter(self,fileName):
self.videoWriter = cv2.VideoWriter(fileName,fourcc=cv2.VideoWriter_fourcc(*'XVID'),fps=30.0,frameSize=(640,480),isColor=True)
def startRecording(self,fileName):
self.createVideoWriter(fileName)
self.setVideoWritingEnabled(True)
print('Start recording' + fileName)
def stopRecording(self):
self.setStateSnapshotEnabled(False)
self.videoWriter.release()
print('Stop recording.')
#==============================================================================================
# <Filters>
# Define the filters in filterlib.py
#==============================================================================================
def createFilterRouting(self,text):
self.filterRouting = []
for line in text:
line = line.split('//')[0] # strip after //
line = line.strip() # strip spaces at both ends
match = re.match(r"(?P<function>[a-z0-9_]+)\((?P<args>.*)\)", line)
if match:
name = match.group('function')
args = match.group('args')
args = re.sub(r'\s+', '', args) # strip spaces in args
self.filterRouting.append({'filterName': name, 'args': args})
def processFilters(self,image):
for item in self.filterRouting:
image = getattr(filterlib,item['filterName'],filterlib.filterNotDefined)(image,item['args'])
# You can add custom filters here if you don't want to use the editor
return image
#==============================================================================================
# <object detection>
# Object detection algorithm is executed after all the filters
# It is assumed that "imageFiltered" is used for detection purpose only;
# the boundary of the detected object will be drawn on "imageOriginal".
# information of detected objects can be stored in an instance of "Agent" class.
#==============================================================================================
def processObjectDetection(self,imageFiltered,imageOriginal):
# convert to rgb so that coloured lines can be drawn on top
imageOriginal = filterlib.color(imageOriginal)
# object detection algorithm starts here
# In this function, information about the agent will be updated, and the original image with
# the detected objects highlighted will be returned
algorithm = getattr(objectDetection,self._detectionAlgorithm,objectDetection.algorithmNotDefined)
imageProcessed = algorithm(imageFiltered,imageOriginal,self.agent1) # pass instances of Agent class if you want to update its info
return imageProcessed
#==============================================================================================
# <subthread drawing>
# Used to draw lines etc. on a plot
# For showing the path that the robot wants to follow
#==============================================================================================
def clearDrawingRouting(self):
self.drawingRouting = []
def addDrawing(self,name,args=None):
self.drawingRouting.append({'drawingName': name, 'args': args})
def processDrawings(self,image):
# convert to rgb so that coloured lines can be drawn on top
image = filterlib.color(image)
for item in self.drawingRouting:
image = getattr(drawing,item['drawingName'],drawing.drawingNotDefined)(image,item['args'])
return image