forked from atelier-ritz/CoilSystemPython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvision.py
245 lines (212 loc) · 10.5 KB
/
vision.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
"""
=============================================================================
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, sys, re, time
from pydc1394 import Camera
import filterlib
import drawing
import objectDetection
from objectDetection import Agent
#=============================================================================================
# 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))
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.filterRouting = [] # data structure: {"filterName", "args"}, defined in the GUI text editor
# 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
if self.isFireWire():
self.cam = Camera(guid=self._guid)
print("====================================================")
print("CameraId:", self._id)
print("Model:", self.cam.model)
print("GUID:", self.cam.guid)
print("Mode:", self.cam.mode)
print("Framerate: ", self.cam.rate)
print("====================================================")
self.cam.start_capture(bufsize=buffersize)
self.cam.start_video()
else:
self.cap = cv2.VideoCapture(0)
if not self.cap.isOpened():
print('Camera is not detected. End program.')
self.cap.release()
sys.exit()
cv2.namedWindow(self.windowName(),16) # cv2.GUI_NORMAL = 16
cv2.moveWindow(self.windowName(), 600,-320+340*self._id);
cv2.setMouseCallback(self.windowName(),showClickedCoordinate)
def updateFrame(self):
if self.isFireWire():
if self.isUpdating():
frameOriginal = self.cam.dequeue()
if not self.isFilterBypassed() and not self.filterRouting == []:
frameFiltered = self.processFilters(frameOriginal.copy())
else:
frameFiltered = frameOriginal
if self.isObjectDetectionEnabled():
frameProcessed = self.processObjectDetection(frameFiltered,frameOriginal)
else:
frameProcessed = frameFiltered
if self.isDrawingEnabled():
frameProcessed = self.processDrawings(frameProcessed)
if self.isSnapshotEnabled():
cv2.imwrite('snapshot.png',filterlib.color(frameProcessed))
self.setStateSnapshotEnabled(False)
if self.isVideoWritingEnabled():
self.videoWriter.write(filterlib.color(frameProcessed))
cv2.imshow(self.windowName(),frameProcessed)
frameOriginal.enqueue()
else:
if self.isUpdating():
_, frameOriginal = self.cap.read()
if not self.isFilterBypassed() and not self.filterRouting == []:
frameFiltered = self.processFilters(frameOriginal.copy())
else:
frameFiltered = frameOriginal
if self.isObjectDetectionEnabled():
frameProcessed = self.processObjectDetection(frameFiltered,frameOriginal)
else:
frameProcessed = frameFiltered
if self.isDrawingEnabled():
frameProcessed = self.processDrawings(frameProcessed)
if self.isSnapshotEnabled():
cv2.imwrite('snapshot.png',filterlib.color(frameProcessed))
self.setStateSnapshotEnabled(False)
if self.isVideoWritingEnabled():
self.videoWriter.write(filterlib.color(frameProcessed))
cv2.imshow(self.windowName(),frameProcessed)
def closeCamera(self):
if self.isFireWire():
self.cam.stop_video()
else:
self.cap.release()
if not self.videoWriter == None:
self.videoWriter.release()
self.videoWriter = None
cv2.destroyWindow(self.windowName())
#==============================================================================================
# 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
#==============================================================================================
# 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