-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpysolovideo.py
1703 lines (1372 loc) · 62.9 KB
/
pysolovideo.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 -*-
#
# pvg.py pysolovideogui
#
#
# Copyright 2011 Giorgio Gilestro <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
"""Version 1.0
Interaction with webcam: opencv liveShow.py / imageAquisition.py
Saving movies as stream: opencv realCam
Saving movies as single files: ? realCam
Opening movies as avi: opencv virtualCamMovie
Opening movies as sequence of files: PIL virtualCamFrames
Each Monitor has a camera that can be: realCam || VirtualCamMovies || VirtualCamFrames
The class monitor is handling the motion detection and data processing while the CAM only handle
IO of image sources
Algorithm for motion analysis: PIL through kmeans (vector quantization)
http://en.wikipedia.org/wiki/Vector_quantization
http://stackoverflow.com/questions/3923906/kmeans-in-opencv-python-interface
"""
import inspect # debug
import cv2, cv
import cPickle
import os, datetime, time
import numpy as np
pySoloVideoVersion ='dev'
MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug','Sep', 'Oct', 'Nov', 'Dec']
def getCameraCount():
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
FIX THIS
"""
n = 0
Cameras = True
while Cameras:
try:
# print ( cv.CaptureFromCAM(n) )
n += 1
except:
Cameras = False
return n
class Cam:
"""
Functions and properties inherited by all cams
"""
def __addText__(self, frame, text = None):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Add current time as stamp to the image
"""
if not text: text = time.asctime(time.localtime(time.time()))
normalfont = cv.InitFont(cv.CV_FONT_HERSHEY_PLAIN, 1, 1, 0, 1, 8)
boldfont = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 3, 8)
font = normalfont
textcolor = (255,255,255)
(x1, _), ymin = cv.GetTextSize(text, font)
width, height = frame.width, frame.height
x = width - x1 - (width/64)
y = height - ymin - 2
cv.PutText(frame, text, (x, y), font, textcolor)
return frame
def getResolution(self):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Returns frame resolution as tuple (w,h)
"""
return self.resolution
def saveSnapshot(self, filename, quality=90, timestamp=False):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
"""
# print('class cam, def savesnapshot, getimage(timestamp,imgtype)') # debug
img = self.getImage(timestamp, imgType)
cv.SaveImage(filename, img) #with opencv
def close(self):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
"""
pass
class realCam(Cam):
"""
a realCam class will handle a webcam connected to the system
camera is handled through opencv and images can be transformed to PIL
"""
def __init__(self, devnum=0, resolution=(640,480)):
# print inspect.currentframe().f_back.f_locals['self'] # debug
self.devnum=devnum
self.resolution = resolution
self.scale = False
self.__initCamera()
def __initCamera(self):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
"""
self.camera = cv.CaptureFromCAM(self.devnum)
self.setResolution (self.resolution)
def getFrameTime(self):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
"""
return time.time() #current time epoch in secs.ms
def addTimeStamp(self, img):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
"""
return self.__addText__(img)
def setResolution(self, (x, y)):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Set resolution of the camera we are acquiring from
"""
x = int(x); y = int(y)
self.resolution = (x, y)
cv.SetCaptureProperty(self.camera, cv.CV_CAP_PROP_FRAME_WIDTH, x)
cv.SetCaptureProperty(self.camera, cv.CV_CAP_PROP_FRAME_HEIGHT, y)
x1, y1 = self.getResolution()
self.scale = ( (x, y) != (x1, y1) ) # if the camera does not support resolution, we need to scale the image
def getResolution(self):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Return real resolution
"""
x1 = cv.GetCaptureProperty(self.camera, cv.CV_CAP_PROP_FRAME_WIDTH)
y1 = cv.GetCaptureProperty(self.camera, cv.CV_CAP_PROP_FRAME_HEIGHT)
return (int(x1), int(y1))
def getImage( self, timestamp=False):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Returns frame
timestamp False (Default) Does not add timestamp
True Add timestamp to the image
"""
#frame = None
if not self.camera:
self.__initCamera()
frame = cv.QueryFrame(self.camera)
if self.scale:
newsize = cv.CreateImage(self.resolution , cv.IPL_DEPTH_8U, 3)
if type(frame) != type(newsize):
return newsize
cv.Resize(frame, newsize)
frame = newsize
if timestamp: frame = self.__addText__(frame)
return frame
def isLastFrame(self):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Added for compatibility with other cams
"""
return False
def close(self):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Closes the connection
"""
print "attempting to close stream"
del(self.camera) #cv.ReleaseCapture(self.camera)
self.camera = None
class virtualCamMovie(Cam):
"""
A Virtual cam to be used to pick images from a movie (avi, mov) rather than a real webcam
Images are handled through opencv
"""
def __init__(self, path, step = None, start = None, end = None, loop=False, resolution=None):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Specifies some of the parameters for working with the movie:
path the path to the file
step distance between frames. If None, set 1
start start at frame. If None, starts at first
end end at frame. If None, ends at last
loop False (Default) Does not playback movie in a loop
True Playback in a loop
"""
self.path = path
if start < 0: start = 0
self.start = start or 0
self.currentFrame = self.start
self.step = step or 1
if self.step < 1: self.step = 1
self.loop = loop
self.capture = cv.CaptureFromFile(self.path)
#finding the input resolution
w = cv.GetCaptureProperty(self.capture, cv.CV_CAP_PROP_FRAME_WIDTH)
h = cv.GetCaptureProperty(self.capture, cv.CV_CAP_PROP_FRAME_HEIGHT)
self.in_resolution = (int(w), int(h))
self.resolution = self.in_resolution
# setting the output resolution
self.setResolution(*resolution)
self.totalFrames = self.getTotalFrames()
if end < 1 or end > self.totalFrames: end = self.totalFrames
self.lastFrame = end
self.blackFrame = cv.CreateImage(self.resolution , cv.IPL_DEPTH_8U, 3)
cv.Zero(self.blackFrame)
def getFrameTime(self, asString=None):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Return the time of the frame
"""
frameTime = cv.GetCaptureProperty(self.capture, cv.CV_CAP_PROP_POS_MSEC)
if asString:
frameTime = str( datetime.timedelta(seconds=frameTime / 100.0) )
return '%s - %s/%s' % (frameTime, self.currentFrame, self.totalFrames) #time.asctime(time.localtime(fileTime))
else:
return frameTime / 1000.0 #returning seconds compatibility reasons
def getImage(self, timestamp=False):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Returns frame
timestamp False (Default) Does not add timestamp
True Add timestamp to the image
"""
#cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_POS_FRAMES, self.currentFrame)
# this does not work properly. Image is very corrupted
im = cv.QueryFrame(self.capture)
if not im: im = self.blackFrame
self.currentFrame += self.step
#elif self.currentFrame > self.lastFrame and not self.loop: return False
if self.scale:
newsize = cv.CreateImage(self.resolution , cv.IPL_DEPTH_8U, 3)
cv.Resize(im, newsize)
im = newsize
if timestamp:
text = self.getFrameTime(asString=True)
im = self.__addText__(im, text)
return im
def setResolution(self, w, h):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Changes the output resolution
"""
self.resolution = (w, h)
self.scale = (self.resolution != self.in_resolution)
def getTotalFrames(self):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Returns total number of frames
Be aware of this bug
https://code.ros.org/trac/opencv/ticket/851
"""
return cv.GetCaptureProperty( self.capture , cv.CV_CAP_PROP_FRAME_COUNT )
def isLastFrame(self):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Are we processing the last frame in the movie?
"""
if ( self.currentFrame >= self.totalFrames ) and not self.loop:
return True
elif ( self.currentFrame >= self.totalFrames ) and self.loop:
self.currentFrame = self.start
return False
else:
return False
class virtualCamFrames(Cam):
"""
A Virtual cam to be used to pick images from a folder rather than a webcam
Images are handled through PIL
"""
def __init__(self, path, resolution = None, step = None, start = None, end = None, loop = False):
# print inspect.currentframe().f_back.f_locals['self'] # debug
self.path = path
self.fileList = self.__populateList__(start, end, step)
self.totalFrames = len(self.fileList)
self.currentFrame = 0
self.last_time = None
self.loop = False
fp = os.path.join(self.path, self.fileList[0])
self.in_resolution = cv.GetSize(cv.LoadImage(fp))
if not resolution: resolution = self.in_resolution
self.resolution = resolution
self.scale = (self.in_resolution != self.resolution)
def getFrameTime(self, asString=None):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Return the time of most recent content modification of the file fname
"""
n = self.currentFrame
fname = os.path.join(self.path, self.fileList[n])
manual = False
if manual:
return self.currentFrame
if fname and asString:
fileTime = os.stat(fname)[-2]
return time.asctime(time.localtime(fileTime))
elif fname and not asString:
fileTime = os.stat(fname)[-2]
return fileTime
def __populateList__(self, start, end, step):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Populate the file list
"""
fileList = []
fileListTmp = os.listdir(self.path)
for fileName in fileListTmp:
if '.tif' in fileName or '.jpg' in fileName:
fileList.append(fileName)
fileList.sort()
return fileList[start:end:step]
def getImage(self, timestamp=False):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Returns frame
timestamp False (Default) Does not add timestamp
True Add timestamp to the image
"""
n = self.currentFrame
fp = os.path.join(self.path, self.fileList[n])
self.currentFrame += 1
try:
im = cv.LoadImage(fp) #using cv to open the file
except:
print ( 'error with image %s' % fp )
raise
if self.scale:
newsize = cv.CreateMat(self.resolution[0], self.resolution[1], cv.CV_8UC3)
cv.Resize(im, newsize)
self.last_time = self.getFrameTime(asString=True)
if timestamp:
im = self.__addText__(im, self.last_time)
return im
def getTotalFrames(self):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Return the total number of frames
"""
return self.totalFrames
def isLastFrame(self):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Are we processing the last frame in the folder?
"""
if (self.currentFrame == self.totalFrames) and not self.loop:
return True
elif (self.currentFrame == self.totalFrames) and self.loop:
self.currentFrame = 0
return False
else:
return False
def setResolution(self, w, h):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Changes the output resolution
"""
self.resolution = (w, h)
self.scale = (self.resolution != self.in_resolution)
def compressAllImages(self, compression=90, resolution=(960,720)):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
FIX THIS: is this needed?
Load all images one by one and save them in a new folder
"""
x,y = resolution[0], resolution[1]
if self.isVirtualCam:
in_path = self.cam.path
out_path = os.path.join(in_path, 'compressed_%sx%s_%02d' % (x, y, compression))
os.mkdir(out_path)
for img in self.cam.fileList:
f_in = os.path.join(in_path, img)
im = Image.open(f_in)
if im.size != resolution:
im = im.resize(resolution, Image.ANTIALIAS)
f_out = os.path.join(out_path, img)
im.save (f_out, quality=compression)
return True
else:
return False
class Arena():
"""
The arena define the space where the flies move
Carries information about the ROI (coordinates defining each vial) and
the number of flies in each vial
The class monitor takes care of the camera
The class arena takes care of the flies
"""
def __init__(self, parent):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena __init__') # debug
self.monitor = parent
self.ROIS = [] #Regions of interest
self.beams = [] # beams: absolute coordinates
self.trackType = 1
self.ROAS = [] #Regions of Action
self.minuteFPS = []
self.period = 60 #in seconds
self.ratio = 0
self.rowline = 0
self.points_to_track = []
#(-1,-1)
self.firstPosition = (0,0)
# shape ( self.period (x,y )
self.__fa = np.zeros( (self.period, 2), dtype=np.int )
# shape ( flies, seconds, (x,y) ) Contains the coordinates of the last second (if fps > 1, average)
self.flyDataBuffer = np.zeros( (1, 2), dtype=np.int )
# shape ( flies, self.period, (x,y) ) Contains the coordinates of the last minute (or period)
self.flyDataMin = np.zeros( (1, self.period, 2), dtype=np.int )
self.count_seconds = 0
self.__n = 0
self.outputFile = None
def __relativeBeams(self):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena __relativebeams') # debug
"""
Return the coordinates of the beam
relative to the ROI to which they belong
"""
newbeams = []
for ROI, beam in zip(self.ROIS, self.beams):
rx, ry = self.__ROItoRect(ROI)[0]
(bx0, by0), (bx1, by1) = beam
newbeams.append( ( (bx0-rx, by0-ry), (bx1-rx, by1-ry) ) )
return newbeams
def __ROItoRect(self, coords):
# # print inspect.currentframe().f_back.f_locals['self'] # debug
# # print(' called Arena __roitorect') # debug
"""
Used internally
Converts a ROI (a tuple of four points coordinates) into
a Rect (a tuple of two points coordinates)
"""
(x1, y1), (x2, y2), (x3, y3), (x4, y4) = coords
lx = min([x1,x2,x3,x4])
rx = max([x1,x2,x3,x4])
uy = min([y1,y2,y3,y4])
ly = max([y1,y2,y3,y4])
# print('will return: ', ( (lx,uy), (rx, ly) )) # debug
return ( (lx,uy), (rx, ly) )
def __distance( self, (x1, y1), (x2, y2) ):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' Arena __distance') # debug
"""
Calculate the distance between two cartesian points
"""
# print('will return: ')
# print(np.sqrt((x2-x1)**2 + (y2-y1)**2)) # debug
return np.sqrt((x2-x1)**2 + (y2-y1)**2)
def __getMidline (self, coords):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena __getmidline') # debug
"""
Return the position of each ROI's midline
Will automatically determine the orientation of the vial
"""
(x1,y1), (x2,y2) = self.__ROItoRect(coords)
horizontal = abs(x2 - x1) > abs(y2 - y1)
if horizontal:
xm = x1 + (x2 - x1)/2
return (xm, y1), (xm, y2)
else:
ym = y1 + (y2 - y1)/2
return (x1, ym), (x2, ym)
def calibrate(self, p1, p2, cm=1):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena calibrate') # debug
"""
The distance between p1 and p2 will be set to be X cm
(default 1 cm)
"""
cm = float(cm)
dpx = self.__distance(p1, p2)
self.ratio = dpx / cm
return self.ratio
def pxToCm(self, distance_px):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena __pxtocm') # debug
"""
Converts distance from pixels to cm
"""
# print(distance_px / self.ratio) # debug
if self.ratio:
return distance_px / self.ratio
else:
print "You need to calibrate the mask first!"
return distance_px
def addROI(self, coords, n_flies):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena addroi') # debug
"""
Add a new ROI to the arena
"""
self.ROIS.append( coords )
self.beams.append ( self.__getMidline (coords) )
self.points_to_track.append(n_flies)
#these increase by one on the fly axis
self.flyDataBuffer = np.append( self.flyDataBuffer, [self.firstPosition], axis=0) # ( flies, 1, (x,y) )
self.flyDataMin = np.append (self.flyDataMin, [self.__fa.copy()], axis=0) # ( flies, self.period, (x,y) )
def getROI(self, n):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena getroi') # debug
"""
Returns the coordinates of the nth crop area
"""
if n > len(self.ROIS):
coords = []
else:
coords = self.ROIS[n]
return coords
def delROI(self, n):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena delroi') # debug
"""
removes the nth crop area from the list
if n -1, remove all
"""
if n >= 0:
self.ROIS.pop(n)
self.points_to_track.pop(n)
self.flyDataBuffer = np.delete( self.flyDataBuffer, n, axis=0)
self.flyDataMin = np.delete( self.flyDataMin, n, axis=0)
elif n < 0:
self.ROIS = []
def getROInumber(self):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena getroinumber') # debug
"""
Return the number of current active ROIS
"""
return len(self.ROIS)
def saveROIS(self, filename):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena saverois') # debug
"""
Save the current crop data to a file
"""
cf = open(filename, 'w')
cPickle.dump(self.ROIS, cf)
cPickle.dump(self.points_to_track, cf)
cf.close()
def loadROIS(self, filename):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena loadrois') # debug
"""
Load the crop data from a file
"""
try:
cf = open(filename, 'r')
self.ROIS = cPickle.load(cf)
self.points_to_track = cPickle.load(cf)
cf.close()
f = len(self.ROIS)
self.flyDataBuffer = np.zeros( (f,2), dtype=np.int )
self.flyDataMin = np.zeros ( (f,self.period,2), dtype=np.int )
for coords in self.ROIS:
self.beams.append ( self.__getMidline (coords) )
return True
except:
return False
def resizeROIS(self, origSize, newSize):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena resizerois') # debug
"""
Resize the mask to new size so that it would properly fit
resized images
"""
newROIS = []
ox, oy = origSize
nx, ny = newSize
xp = float(ox) / nx
yp = float(oy) / ny
for ROI in self.ROIS:
nROI = []
for pt in ROI:
nROI.append ( (pt[0]*xp, pt[1]*yp) )
newROIS.append ( ROI )
return newROIS
def point_in_poly(self, pt, poly):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena point_in_poly') # debug
"""
Determine if a point is inside a given polygon or not
Polygon is a list of (x,y) pairs. This fuction
returns True or False. The algorithm is called
"Ray Casting Method".
polygon = [(x,y),(x1,x2),...,(x10,y10)]
http://pseentertainmentcorp.com/smf/index.php?topic=545.0
Alternatively:
http://opencv.itseez.com/doc/tutorials/imgproc/shapedescriptors/point_polygon_test/point_polygon_test.html
"""
x, y = pt
n = len(poly)
inside = False
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x,p1y = p2x,p2y
return inside
def isPointInROI(self, pt):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena ispointinroi') # debug
"""
Check if a given point falls whithin one of the ROI
Returns the ROI number or else returns -1
"""
for ROI in self.ROIS:
if self.point_in_poly(pt, ROI):
return self.ROIS.index(ROI)
return -1
def ROIStoRect(self):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena roistorect') # debug
"""
translate ROI (list containing for points a tuples)
into Rect (list containing two points as tuples)
"""
newROIS = []
for ROI in self.ROIS:
newROIS. append ( self.__ROItoRect(ROI) )
return newROIS
def getLastSteps(self, fly, steps):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena getlaststeps') # debug
"""
"""
c = self.count_seconds
return [(x,y) for [x,y] in self.flyDataMin[fly][c-steps:c].tolist()] + [tuple(self.flyDataBuffer[fly].flatten())]
def addFlyCoords(self, count, fly):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Add the provided coordinates to the existing list
count int the fly number in the arena
fly (x,y) the coordinates to add
Called for every fly moving in every frame
"""
fly_size = 15 #About 15 pixels at 640x480
max_movement= fly_size * 100
min_movement= fly_size / 3
previous_position = tuple(self.flyDataBuffer[count])
isFirstMovement = ( previous_position == self.firstPosition )
fly = fly or previous_position #Fly is None if no blob was detected
distance = self.__distance( previous_position, fly )
if ( distance > max_movement and not isFirstMovement ) or ( distance < min_movement ):
fly = previous_position
#Does a running average for the coordinates of the fly at each frame to flyDataBuffer
#This way the shape of flyDataBuffer is always (n, (x,y)) and once a second we just have to add the (x,y)
#values to flyDataMin, whose shape is (n, 60, (x,y))
self.flyDataBuffer[count] = np.append( self.flyDataBuffer[count], fly, axis=0 ).reshape(-1,2).mean(axis=0)
if count == 0: print('------------------------------------------------------------')
print('ROI_num = ',count,' fly = ',fly,'previous position = ',previous_position,'distance = ',distance) # debug
return fly, distance
def compactSeconds(self, FPS, delta):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena compactseconds') # debug
"""
Compact the frames collected in the last second
by averaging the value of the coordinates
Called every second; flies treated at once
FPS current rate of frame per seconds
delta how much time has elapsed from the last "second"
"""
self.minuteFPS.append(FPS)
self.flyDataMin[:,self.__n] = self.flyDataBuffer
if self.count_seconds + 1 >= self.period:
self.writeActivity( fps = np.mean(self.minuteFPS) )
self.count_seconds = 0
self.__n = 0
self.minuteFPS = []
for i in range(0,self.period):
self.flyDataMin[:,i] = self.flyDataBuffer
#growing continously; this is the correct thing to do but we would have problems adding new row with new ROIs
#self.flyDataMin = np.append(self.flyDataMin, self.flyDataBuffer, axis=1)
self.count_seconds += delta
self.__n += 1
def writeActivity(self, fps=0, extend=True):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena writeactivity') # debug
"""
Write the activity to file
Kind of motion depends on user settings
Called every minute; flies treated at once
1 09 Dec 11 19:02:19 1 0 1 0 0 0 ? [actual_activity]
"""
# print('writeactivity') # debug
#Here we build the header
#year, month, day, hh, mn, sec = time.localtime()[0:6]
dt = datetime.datetime.fromtimestamp( self.monitor.getFrameTime() ) # NOT GETTING CORRECT date/time info
year, month, day, hh, mn, sec = dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second
month = MONTHS[month-1]
#0 rowline
#1 date
date = '%02d %s %s' % (day, month, str(year)[-2:])
# print(date) # debug
#2 time
tt = '%02d:%02d:%02d' % (hh, mn, sec)
# print(tt) # debug
#3 monitor is active
active = '1'
#4 average frames per seconds (FPS)
damscan = int(round(fps))
#5 tracktype
tracktype = self.trackType
#6 is a monitor with sleep deprivation capabilities?
sleepDep = self.monitor.isSDMonitor * 1
# print('sleepdep = ') # debug
# print(sleepDep) # debug
#7 monitor number, not yet implemented
monitor = '0'
#8 unused
unused = 0
#9 is light on or off
light = '0' # changed to 0 from ? for compatability with SCAMP
#10 :
#activity
activity = []
row = ''
if self.trackType == 0:
activity = [self.calculateDistances(),]
elif self.trackType == 1:
activity = [self.calculateVBM(),]
elif self.trackType == 2:
activity = self.calculatePosition()
# print('activity = ', activity) # debug
# Expand the readings to 32 flies for compatibility reasons with trikinetics
flies = len ( activity[0].split('\t') )
if extend and flies < 32:
extension = '\t' + '\t'.join(['0',] * (32-flies) )
else:
extension = ''
# print('extension = ')
# # print(extension) # debug
for line in activity:
self.rowline +=1
row_header = '%s\t'*10 % (self.rowline, date, tt, active, damscan, tracktype, sleepDep, monitor, unused, light)
row += row_header + line + extension + '\n'
if self.outputFile:
print('outputfile: ',self.outputFile)
fh = open(self.outputFile, 'a')
print('output = ',row) # debug
fh.write(row)
# raw_input("Press Enter to continue...") # debug
fh.close()
def calculateDistances(self):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena calculatedistances') # debug
"""
Motion is calculated as distance in px per minutes
"""
# shift by one second left flies, seconds, (x,y)
fs = np.roll(self.flyDataMin, -1, axis=1)
x = self.flyDataMin[:,:,:1]
y = self.flyDataMin[:,:,1:]
x1 = fs[:,:,:1]
y1 = fs[:,:,1:]
d = self.__distance((x,y),(x1,y1))
#we sum everything BUT the last bit of information otherwise we have data duplication
values = d[:,:-1,:].sum(axis=1).reshape(-1)
activity = '\t'.join( ['%s' % int(v) for v in values] )
print('activity = ', activity, 'values = ',values)
return activity
def calculateVBM(self):
# print inspect.currentframe().f_back.f_locals['self'] # debug
# print(' called Arena calculatevbm') # debug
"""
Motion is calculated as virtual beam crossing
Detects automatically beam orientation (vertical vs horizontal)
"""
values = []
for fd, md in zip(self.flyDataMin, self.__relativeBeams()):
(mx1, my1), (mx2, my2) = md
horizontal = (mx1 == mx2)
fs = np.roll(fd, -1, 0)
x = fd[:,:1]; y = fd[:,1:] # THESE COORDINATES ARE RELATIVE TO THE ROI
x1 = fs[:,:1]; y1 = fs[:,1:]
if horizontal:
crossed = (x < mx1 ) * ( x1 > mx1 ) + ( x > mx1) * ( x1 < mx1 )
else:
crossed = (y < my1 ) * ( y1 > my1 ) + ( y > my1) * ( y1 < my1 )
values .append ( crossed.sum() )
activity = '\t'.join( [str(v) for v in values] )
return activity
def calculatePosition(self, resolution=1):
# print inspect.currentframe().f_back.f_locals['self'] # debug
"""
Simply write out position of the fly at every time interval, as
decided by "resolution" (seconds)
"""
activity = []
rois = self.getROInumber()