-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathexamplegui.py
296 lines (228 loc) · 7.27 KB
/
examplegui.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
#!/usr/bin/env python
#Note check this out: http://johnroach.info/2011/03/02/image-capturing-from-webcam-using-opencv-and-pygame-in-python/
from __future__ import print_function
import pygtk, math, array, numpy as np
pygtk.require('2.0')
import gtk, gobject, cv, cairo, opencv, multiprocessing, time, Queue
from PIL import Image
import klt, selectGoodFeatures, writeFeatures, trackFeatures
def IplToPilImg(imIpl):
assert imIpl.nChannels == 3
imgSize = cv.GetSize(imIpl)
return Image.fromstring("RGB", cv.GetSize(imIpl), imIpl.tostring(), 'raw', "BGR")
class WebcamWidget(gtk.Invisible):
def __init__(self):
gtk.Invisible.__init__(self)
self.toWorker, self.fromWorker = multiprocessing.Queue(), multiprocessing.Queue()
self.buffer = []
self.maxBufferSize = 100
self.count = 0
gobject.timeout_add(int(round(1000./50.)), self.UpdatePipe)
self.p = multiprocessing.Process(target=self.PollCamera, args=(self.toWorker,self.fromWorker))
self.p.start()
def __del__(self):
pass
#self.Stop()
def Stop(self):
self.toWorker.put(("STOP",))
self.p.terminate()
def GetCurrentImg(self):
if len(self.buffer) == 0:
return None
return self.buffer[-1]
def GetFrameNum(self):
return self.count
def UpdatePipe(self):
while not self.fromWorker.empty():
try:
pipeData = self.fromWorker.get(0)
ty = pipeData[0]
if ty == "FRAME":
img = pipeData[1]
self.buffer.append(img)
self.count += 1
while len(self.buffer) > self.maxBufferSize:
self.buffer.pop(0)
#print(ty, len(self.buffer))
except Queue.Empty:
pass
return True
def PollCamera(self, toWorker, fromWorker):
running = True
cap = cv.CaptureFromCAM(-1)
capture_size = (320,200)
cv.SetCaptureProperty(cap, cv.CV_CAP_PROP_FRAME_WIDTH, capture_size[0])
cv.SetCaptureProperty(cap, cv.CV_CAP_PROP_FRAME_HEIGHT, capture_size[1])
#fps = cv.GetCaptureProperty(cap, cv.CV_CAP_PROP_FPS)
while (running):
try:
pipeData = toWorker.get(0)
#print("Worker",pipeData[0])
if pipeData[0] == "STOP":
running = False
except Queue.Empty:
pass
imIpl = cv.QueryFrame(cap)
if imIpl is not None:
pilImg = IplToPilImg(imIpl)
# #print(pilImg)
fromWorker.put(("FRAME",np.array(pilImg)))
time.sleep(1./100.)
fromWorker.put(("STOPPED",))
return True
class TrackingProcess:
def __init__(self):
self.currentTracking = []
self.toWorker, self.fromWorker = multiprocessing.Queue(), multiprocessing.Queue()
gobject.timeout_add(int(round(1000./50.)), self.UpdatePipe)
self.p = multiprocessing.Process(target=self.Process, args=(self.toWorker,self.fromWorker))
#self.p = multiprocessing.Process(target=Test, args=(pipeChile,))
self.p.start()
def __del__(self):
pass
def Stop(self):
self.toWorker.put(("STOP",))
self.p.terminate()
def TrackFrame(self, frameArr):
if self.toWorker.qsize() < 5:
self.toWorker.put(("FRAME", frameArr))
def GetCurrentTracking(self):
return self.currentTracking
def UpdatePipe(self):
try:
pipeData = self.fromWorker.get(0)
ty = pipeData[0]
if ty == "TRACKING":
tr = pipeData[1]
self.currentTracking = tr
except Queue.Empty:
pass
return True
def Process(self, toWorker,fromWorker):
running = True
currentFrame = None
tc = klt.KLT_TrackingContext()
tc.sequentialMode = True
tc.retainTrackers = True
fl = []
prevImg = None
while running:
while not toWorker.empty():
print(toWorker.empty(), toWorker.qsize())
try:
pipeData = toWorker.get()
if pipeData[0] == "STOP":
running = False
if pipeData[0] == "FRAME":
currentFrame = Image.fromarray(pipeData[1])
except Queue.Empty:
pass
time.sleep(0.01)
if currentFrame is not None and running:
nFeatures = 50
countActive = klt.KLTCountRemainingFeatures(fl)
if countActive == 0 or prevImg is None:
fl = selectGoodFeatures.KLTSelectGoodFeatures(tc, currentFrame, nFeatures)
else:
trackFeatures.KLTTrackFeatures(tc, prevImg, currentFrame, fl)
fromWorker.put(("TRACKING",fl))
prevImg = currentFrame
currentFrame = None
time.sleep(0.01)
class VisualiseWidget(gtk.DrawingArea):
def __init__(self):
gtk.DrawingArea.__init__(self)
self.image = None
self.trackerPos = []
self.set_size_request(100,100)
self.connect("expose_event", self.expose)
def expose(self, widget, event):
self.context = widget.window.cairo_create()
# set a clip region for the expose event
self.context.rectangle(event.area.x, event.area.y,
event.area.width, event.area.height)
self.context.clip()
self.draw(self.context)
return False
def RedrawCanvas(self):
self.redrawPending = False
if self.window:
alloc = self.get_allocation()
self.queue_draw_area(0, 0, alloc.width, alloc.height)
self.window.process_updates(True)
def draw(self, context):
rect = self.get_allocation()
x = rect.x + rect.width / 2
y = rect.y + rect.height / 2
if self.image is not None:
context.set_source_surface(self.image,
0.,
0.)
context.paint()
#Draw tracker points
context.save()
context.set_source_rgb(0, 1, 0)
for pt in self.trackerPos:
context.arc(pt[0], pt[1], 2., 0. * math.pi, 2. * math.pi)
context.fill()
context.restore()
def SetImageByIpl(self,imIpl):
#Convert IPL image to PIL image
#pilImg = opencv.adaptors.Ipl2PIL(imIpl)
self.SetImageByPil(IplToPilImg(imIpl))
def SetImageByPil(self, pilImg):
#Convert PIL image to cairo surface
pilRaw = array.array('B',pilImg.tostring("raw","BGRX",0,1))
stride = pilImg.size[0] * 4
self.image = cairo.ImageSurface.create_for_data(pilRaw, cairo.FORMAT_RGB24,
pilImg.size[0], pilImg.size[1], stride)
self.set_size_request(*pilImg.size)
class Base:
def __init__(self):
self.tc = klt.KLT_TrackingContext()
self.fl = []
self.webcam = WebcamWidget()
self.showingFrame = None
self.trackingProcess = TrackingProcess()
#Create main window
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.connect("delete_event", self.delete_event)
self.window.connect("destroy", self.destroy)
self.window.set_border_width(10)
self.visArea = VisualiseWidget()
#self.visArea.set_size_request((100,100))
#self.visArea.set_from_file("img0.pgm")
self.window.add(self.visArea)
self.window.show_all()
gobject.timeout_add(int(round(1000./25.)), self.UpdateImage)
def delete_event(self, widget, event, data=None):
self.webcam.Stop()
self.trackingProcess.Stop()
print("delete event occurred")
return False
def destroy(self, widget, data=None):
print("destroy window")
gtk.main_quit()
def main(self):
gtk.main()
def UpdateImage(self):
#print("x")
#cv.GrabFrame(self.cap)
#imIpl = cv.RetrieveFrame(self.cap)
if self.showingFrame != self.webcam.GetFrameNum():
img = self.webcam.GetCurrentImg()
if img is not None:
self.visArea.SetImageByPil(Image.fromarray(img))
currentTracking = self.trackingProcess.GetCurrentTracking()
#print(currentTracking)
self.visArea.trackerPos = []
for pt in currentTracking:
if pt.val < 0: continue
self.visArea.trackerPos.append((pt.x,pt.y))
self.visArea.RedrawCanvas()
self.trackingProcess.TrackFrame(img)
self.showingFrame = self.webcam.GetFrameNum()
return True
if __name__ == "__main__":
base = Base()
base.main()