forked from sightmachine/SimpleCV
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTemporalColorTracker.py
More file actions
400 lines (358 loc) · 15.6 KB
/
Copy pathTemporalColorTracker.py
File metadata and controls
400 lines (358 loc) · 15.6 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
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
from SimpleCV import Image, ImageSet, Camera, VirtualCamera, ROI, Color, LineScan
import numpy as np
import scipy.signal as sps
import warnings
import time as time
class TemporalColorTracker:
"""
**SUMMARY**
The temporal color tracker attempts to find and periodic color
signal in an roi or arbitrary function. Once the temporal tracker is
trained it will return a count object every time the signal is detected.
This class is usefull for counting periodically occuring events, for example,
waves on a beach or the second hand on a clock.
"""
def __init__(self):
self._rtData = LineScan([]) # the deployed data
self._steadyState = None # mu/signal for the ss behavior
self._extractor = None
self._roi = None
self._window = None
self._template = None
self._cutoff = None
self._bestKey = None
self._isPeak = False
self.corrTemplates = None
self.peaks = {}
self.valleys = {}
self.doPeaks = {}
self.corrStdMult = 3.0
self.count = 0
def train(self,src,roi=None, extractor=None, doCorr=False, maxFrames=1000,
ssWndw=0.05, pkWndw=30, pkDelta=3, corrStdMult=2.0, forceChannel=None, verbose=True):
"""
**SUMMARY**
To train the TemporalColorTracker you provide it with a video, camera, or ImageSet and either
an region of interest (ROI) or a function of the form:
(R,G,B) = MyFunction(Image)
This function takes in an image and returns a tuple of RGB balues for the frame.
The TemoralColroTracker will then attempt to find the maximum peaks in the data
and create a model for the peaks.
**PARAMETERS**
* *src* - An image source, either a camera, a virtual camera (like a video) or
an ImageSet.
* *roi* - An ROI object that tells the tracker where to look in the frame.
* *extractor* - A function with the following signature:
(R,G,B) = Extract(Image)
* *doCorr* - Do correlation use correlation to confirm that the signal is present.
* *maxFrames* - The maximum number of frames to use for training.
* *ssWndw* - SteadyState window, this is the size of the window to look for a steady
state, i.e a region where the signal is not changing.
* *pkWndw* - The window size to look for peaks/valleys in the signal. This is roughly
the period of the signal.
* *pkDelta* - The minimum difference between the steady state to look for peaks.
* *corrStdMult* - The maximum correlation standard deviation of the training set
to use when looking for a signal. This is the knob to dial in when using correlation
to confirm the event happened.
* *forceChannel* - A string that is the channel to use. Options are:
* 'r' - Red Channel
* 'g' - Green Channel
* 'b' - Blue Channel
* 'h' - Hue Channel
* 'i' - Intensity Channel
By default this module will look at the signal with the highest peak/valley swings.
You can manually overide this behavior.
* *verbose* - Print debug info after training.
**RETURNS**
Nothing, will raise an exception if no signal is found.
**EXAMPLE**
A really simple example
>>>> cam = Camera(1)
>>>> tct = TemporalColorTracker()
>>>> img = cam.getImage()
>>>> roi = ROI(img.width*0.45,img.height*0.45,img.width*0.1,img.height*0.1,img)
>>>> tct.train(cam,roi=roi,maxFrames=250)
>>>> disp = Display((800,600))
>>>> while disp.isNotDone():
>>>> img = cam.getImage()
>>>> result = tct.recognize(img)
>>>> roi = ROI(img.width*0.45,img.height*0.45,img.width*0.1,img.height*0.1,img)
>>>> roi.draw(width=3)
>>>> img.drawText(str(result),20,20,color=Color.RED,fontsize=32)
>>>> img = img.applyLayers()
>>>> img.save(disp)
"""
if( roi is None and extractor is None ):
raise Exception('Need to provide an ROI or an extractor')
self.doCorr = doCorr
self.corrStdMult = corrStdMult
self._extractor = extractor #function that returns a RGB values
self._roi = roi
self._extract(src,maxFrames,verbose)
self._findSteadyState(windowSzPrct=ssWndw)
self._findPeaks(pkWndw,pkDelta)
self._extractSignalInfo(forceChannel)
self._buildSignalProfile()
if verbose:
for key in self.data.keys():
print 30*'-'
print "Channel: {0}".format(key)
print "Data Points: {0}".format(len(self.data[key]))
print "Steady State: {0}+/-{1}".format(self._steadyState[key][0],self._steadyState[key][1])
print "Peaks: {0}".format(self.peaks[key])
print "Valleys: {0}".format(self.valleys[key])
print "Use Peaks: {0}".format(self.doPeaks[key])
print 30*'-'
print "BEST SIGNAL: {0}".format(self._bestKey)
print "BEST WINDOW: {0}".format(self._window)
print "BEST CUTOFF: {0}".format(self._cutoff)
def _getDataFromImg(self,img):
"""
Get the data from the image
"""
mc = None
if( self._extractor ):
mc = self._extractor(img)
else:
temp = self._roi.reassign(img)
mc = temp.meanColor()
self.data['r'].append(mc[0])
self.data['g'].append(mc[1])
self.data['b'].append(mc[2])
# NEED TO CHECK THAT THIS REALLY RGB
self.data['i'].append(Color.getLightness(mc))
self.data['h'].append(Color.getHueFromRGB(mc))
#return [mc[0],mc[1],mc[2],gray,Color.rgbToHue(mc)]
def _extract(self,src,maxFrames,verbose):
# get the full dataset and append it to the data vector dictionary.
self.data = {'r':[],'g':[],'b':[],'i':[],'h':[]}
if( isinstance(src,ImageSet) ):
src = VirtualCamera(src,st='imageset') # this could cause a bug
elif( isinstance(src,(VirtualCamera,Camera))):
count = 0
for i in range(0,maxFrames):
img = src.getImage()
count = count + 1
if( verbose ):
print "Got Frame {0}".format(count)
if( isinstance(src,Camera) ):
time.sleep(0.05) # let the camera sleep
if( img is None ):
break
else:
self._getDataFromImg(img)
else:
raise Exception('Not a valid training source')
return None
def _findSteadyState(self,windowSzPrct=0.05):
# slide a window across each of the signals
# find where the std dev of the window is minimal
# this is the steady state (e.g. where the
# assembly line has nothing moving)
# save the mean and sd of this value
# as a tuple in the steadyStateDict
self._steadyState = {}
for key in self.data.keys():
wndwSz = int(np.floor(windowSzPrct*len(self.data[key])))
signal = self.data[key]
# slide the window and get the std
data = [np.std(signal[i:i+wndwSz]) for i in range(0,len(signal)-wndwSz)]
# find the first spot where sd is minimal
index = np.where(data==np.min(data))[0][0]
# find the mean for the window
mean = np.mean(signal[index:index+wndwSz])
self._steadyState[key]=(mean,data[index])
def _findPeaks(self,pkWndw,pkDelta):
"""
Find the peaks and valleys in the data
"""
self.peaks = {}
self.valleys = {}
for key in self.data.keys():
ls = LineScan(self.data[key])
# need to automagically adjust the window
# to make sure we get a minimum number of
# of peaks, maybe let the user guess a min?
self.peaks[key]=ls.findPeaks(pkWndw,pkDelta)
self.valleys[key]=ls.findValleys(pkWndw,pkDelta)
def _extractSignalInfo(self,forceChannel):
"""
Find the difference between the peaks and valleys
"""
self.pD = {}
self.vD = {}
self.doPeaks = {}
bestSpread = 0.00
bestDoPeaks = None
bestKey = None
for key in self.data.keys():
#Look at which signal has a bigger distance from
#the steady state behavior
if( len(self.peaks[key]) > 0 ):
peakMean = np.mean(np.array(self.peaks[key])[:,1])
self.pD[key] = np.abs(self._steadyState[key][0]-peakMean)
else:
self.pD[key] = 0.00
if( len(self.valleys[key]) > 0 ):
valleyMean = np.mean(np.array(self.valleys[key])[:,1])
self.vD[key] = np.abs(self._steadyState[key][0]-valleyMean)
else:
self.vD[key] = 0.00
self.doPeaks[key]=False
best = self.vD[key]
if( self.pD[key] > self.vD[key] ):
best = self.pD[key]
self.doPeaks[key] = True
if( best > bestSpread ):
bestSpread = best
bestDoPeaks = self.doPeaks[key]
bestKey = key
# Now we know which signal has the most spread
# and what direction we are looking for.
if( forceChannel is not None ):
if(self.data.has_key(forceChannel)):
self._bestKey = forceChannel
else:
raise Exception('That is not a valid data channel')
else:
self._bestKey = bestKey
def _buildSignalProfile(self):
key = self._bestKey
self._window = None
peaks = None
if( self.doPeaks[key] ):
self._isPeak = True
peaks = self.peaks[key]
# We're just going to do halfway
self._cutoff = self._steadyState[key][0]+(self.pD[key]/2.0)
else:
self._isPeak = False
peaks = self.valleys[key]
self._cutoff = self._steadyState[key][0]-(self.vD[key]/2.0)
if( len(peaks) > 1 ):
p2p = np.array(peaks[1:])-np.array(peaks[:-1])
p2pMean = int(np.mean(p2p))
p2pS = int(np.std(p2p))
p2pMean = p2pMean + 2*p2pS
# constrain it to be an od window
if int(p2pMean) % 2 == 1:
p2pMean = p2pMean+1
self._window = p2pMean
else:
raise Exception("Can't find enough peaks")
if( self.doCorr and self._window is not None ):
self._doCorr()
#NEED TO ERROR OUT ON NOT ENOUGH POINTS
def _doCorr(self):
key = self._bestKey
# build an average signal for the peaks and valleys
# centered at the peak. The go and find the correlation
# value of each peak/valley with the average signal
self.corrTemplates = []
halfWndw = self._window/2
pList = None
if( self._isPeak ):
pList = self.peaks[key]
else:
pList = self.valleys[key]
for peak in pList:
center = peak[0]
lb = center-halfWndw
ub = center+halfWndw
# ignore signals that fall of the end of the data
if( lb > 0 and ub < len(self.data[key]) ):
self.corrTemplates.append(np.array(self.data[key][lb:ub]))
if( len(self.corrTemplates) < 1 ):
raise Exception('Could not find a coherrent signal for correlation.')
sig = np.copy(self.corrTemplates[0]) # little np gotcha
for peak in self.corrTemplates[1:]:
sig += peak
self._template = sig / len(self.corrTemplates)
self._template /= np.max(self._template)
corrVals = [np.correlate(peak/np.max(peak),self._template) for peak in self.corrTemplates]
print corrVals
self.corrThresh = (np.mean(corrVals),np.std(corrVals))
def _getBestValue(self,img):
"""
Extract the data from the live signal
"""
if( self._extractor ):
mc = self._extractor(img)
else:
temp = self._roi.reassign(img)
mc = temp.meanColor()
if( self._bestKey == 'r' ):
return mc[0]
elif( self._bestKey == 'g' ):
return mc[1]
elif( self._bestKey == 'b' ):
return mc[2]
elif( self._bestKey == 'i' ):
return Color.getLightness(mc)
elif( self._bestKey == 'h' ):
return Color.getHueFromRGB(mc)
def _updateBuffer(self,v):
"""
Keep a buffer of the running data and process it to determine if there is
a peak.
"""
self._rtData.append(v)
wndwCenter = int(np.floor(self._window/2.0))
# pop the end of the buffer
if( len(self._rtData) > self._window):
self._rtData = self._rtData[1:]
if( self._isPeak ):
lm = self._rtData.findPeaks()
for l in lm:
if( l[0] == wndwCenter and l[1] > self._cutoff ):
if( self.doCorr ):
corrVal = np.correlate(self._rtData.normalize(),self._template)
thresh = self.corrThresh[0]-self.corrStdMult*self.corrThresh[1]
if( corrVal[0] > thresh ):
self.count += 1
else:
self.count += 1
else:
lm = self._rtData.findValleys()
for l in lm:
if( l[0] == wndwCenter and l[1] < self._cutoff ):
if( self.doCorr ):
corrVal = np.correlate(self._rtData.normalize(),self._template)
thresh = self.corrThresh[0]-self.corrStdMult*self.corrThresh[1]
if( corrVal[0] > thresh ):
self.count += 1
else:
self.count += 1
return self.count
def recognize(self,img):
"""
**SUMMARY***
This method is used to do the real time signal analysis. Pass the method
an image from the stream and it will return the event count. Note that
due to buffering the signal may lag the actual video by up to a few seconds.
**PARAMETERS**
* *img* - The image in the stream to test.
**RETURNS**
Returns an int that is the count of the number of times the event has occurred.
**EXAMPLE**
>>>> cam = Camera(1)
>>>> tct = TemporalColorTracker()
>>>> img = cam.getImage()
>>>> roi = ROI(img.width*0.45,img.height*0.45,img.width*0.1,img.height*0.1,img)
>>>> tct.train(cam,roi=roi,maxFrames=250)
>>>> disp = Display((800,600))
>>>> while disp.isNotDone():
>>>> img = cam.getImage()
>>>> result = tct.recognize(img)
>>>> roi = ROI(img.width*0.45,img.height*0.45,img.width*0.1,img.height*0.1,img)
>>>> roi.draw(width=3)
>>>> img.drawText(str(result),20,20,color=Color.RED,fontsize=32)
>>>> img = img.applyLayers()
>>>> img.save(disp)
**TODO**
Return True/False if the event occurs.
"""
if( self._bestKey is None ):
raise Exception('The TemporalColorTracker has not been trained.')
v = self._getBestValue(img)
return self._updateBuffer(v)