This repository has been archived by the owner on Oct 27, 2022. It is now read-only.
forked from gilestrolab/pySolo-Video
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpysolovideo.py
2200 lines (1687 loc) · 66.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.4
Each Monitor has a camera that can be: realCam || VirtualCamMovies || VirtualCamFrames
The class Monitor is handling the motion detection and data processing while the class Cam only handles
IO of image sources
Algorithm for motion analysis:
Versions <1.0
PIL through kmeans (vector quantization)
http://en.wikipedia.org/wiki/Vector_quantization
http://stackoverflow.com/questions/3923906/kmeans-in-opencv-python-interface
Version 1.0
Blob detection through CV
Annoying mem leak associated to CV
#http://opencv-users.1802565.n2.nabble.com/Why-is-cvClearMemStorage-not-exposed-through-the-Python-interface-td7229752.html
Version 1.2
Now all the video processing is handled through CV2, including contour detection
Version 1.3
Classes Arena and Monitor fuse. Class ROImask is born
Current Data format
#0 rowline
#1 date
#2 time
#3 monitor is active (1)
#4 average frames per seconds (FPS)
#5 tracktype (0,1,2)
#6 is a monitor with sleep deprivation capabilities? (n/a)
#7 monitor number, not yet implemented (n/a)
#8 unused
#9 is light on or off (n/a)
#10 actual activity (normally 32 datapoints)
"""
import os, datetime, time
import cPickle, json, sys
from calendar import month_abbr
import cv2
import numpy as np
import io, socket, struct
try:
import picamera
except:
print "no support for picamera"
import threading
from accessories.sleepdeprivator import sleepdeprivator
pySoloVideoVersion ='dev' #will be 1.4
FLY_FIRST_POSITION = (-1,-1)
FLY_NOT_DETECTED = None
PERIOD = 60 #in seconds
ACTIVITY_PERIOD = 1440 #buffer of activity, in minutes
NO_SERIAL_PORT = "NO SD"
MONITORS = []
class runningAvgComparison():
"""
This is a class that stores a running average
and a running STD
For each value that is used to update,
it returns also information on whether it is an outlier
"""
def __init__(self):
"""
"""
self.__tot_sum = 0
self.__n = 0
self.__sq_diff = 0
def update(self, value, outlier=2):
"""
Take a running value and returns:
mean the running mean
std the running standard deviation
distance how distant is the value from the mean
outside a boolean value of whether the value is outside 2 SD
"""
self.__tot_sum += value
self.__n += 1
mean = self.__tot_sum / self.__n
self.__sq_diff += np.square(value - mean)
std = np.sqrt(self.__sq_diff / self.__n) or 1
distance = (value - mean) / std
outside = distance >= outlier
return mean, std, distance, outside
class Cam:
"""
Functions and properties inherited by all cams
"""
def saveSnapshot(self, filename, quality=90, timestamp=False):
"""
"""
frame, _ = self.getImage()
cv2.imwrite(filename, frame)
def close(self):
"""
"""
return 0
def getSerialNumber(self):
"""
"""
return 0
def getBlackFrame( self, resolution=(800,600) ):
"""
"""
w, h = resolution
blackframe = np.zeros( (w, h, 3), dtype = np.uint8)
#blackframe = cv2.cvtColor(blackframe, cv2.GRAY2COLOR_BGR)
cv2.putText(blackframe, "NO INPUT", (int(w/4), int(h/2)), cv2.FONT_HERSHEY_PLAIN, 2, (255,255,255), 1)
return blackframe
class piCamera(Cam):
"""
http://picamera.readthedocs.org/en/latest/api.html
http://www.raspberrypi.org/picamera-pure-python-interface-for-camera-module/
"""
def __init__(self, devnum=0, resolution=(800, 600), use_network=True):
self.camera = 0
self.resolution = resolution
self.scale = False
self.image_queue = self.getBlackFrame(resolution)
if use_network:
self.startNetworkStream()
else:
self.__initCamera()
def __initCamera(self):
"""
"""
self.camera = picamera.PiCamera()
self.camera.resolution = self.resolution
def startNetworkStream(self, port=8000):
"""
"""
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(('', port))
#<<<<<<< HEAD
print ("Live stream socket listening on port {p}...".format(p=port))
#=======
# print "Live stream socket listening on port {p}...".format(p=port)
#>>>>>>> 2c18142d99048230a47ad507b4237c753bbd75ed
self.pipe = None
self.socket.listen(5)
self.socket_thread_1 = threading.Thread(target=self.socket_listen)
#<<<<<<< HEAD
self.socket_thread_1.daemon=True
self.socket_thread_2 = threading.Thread(target=self.socket_stream)
self.socket_thread_2.daemon=True
#=======
# self.socket_thread_2 = threading.Thread(target=self.socket_stream)
#>>>>>>> 2c18142d99048230a47ad507b4237c753bbd75ed
self.keepSocket = True
self.socket_thread_1.start()
self.socket_thread_2.start()
def stopNetworkStream(self):
"""
"""
self.keepSocket = False
def socket_listen(self):
"""
"""
while self.keepSocket:
print "listening"
try:
self.remote, client_address = self.socket.accept()
self.pipe = self.remote.makefile('wb',0)
print "connected to client: " , client_address
except:
pass
def socket_stream(self):
"""
"""
while self.keepSocket:
try:
with picamera.PiCamera() as camera:
camera.resolution = self.resolution
# Start a preview and let the camera warm up for 2 seconds
camera.start_preview()
time.sleep(2)
# Note the start time and construct a stream to hold image data
# temporarily (we could write it directly to connection but in this
# case we want to find out the size of each capture first to keep
# our protocol simple)
stream = io.BytesIO()
for foo in camera.capture_continuous(stream, 'jpeg', use_video_port=True):
data = np.fromstring(stream.getvalue(), dtype=np.uint8)
# "Decode" the image from the array, preserving colour
image = cv2.imdecode(data, 1)
# Convert RGB to BGR
self.image_queue = image[:, :, ::-1]
if self.pipe:
# Write the length of the capture to the stream and flush to
# ensure it actually gets sent
self.pipe.write(struct.pack('<L', stream.tell()))
self.pipe.flush()
# Rewind the stream
stream.seek(0)
if self.pipe:
# send the image data over the pipe
self.pipe.write(stream.read())
# Reset the stream for the next capture
stream.seek(0)
stream.truncate()
# Write a length of zero to the pipe to signal we're done
if self.pipe:
self.pipe.write(struct.pack('<L', 0))
#finally:
# self.pipe.close()
# self.socket.close()
except socket.error, e:
print "Got Socket error", e
self.remote.close()
self.pipe = None
except IOError, e:
print "Got IOError: ", e
self.pipe = None
def close(self):
"""
"""
if self.camera:
self.camera.stop_preview()
self.camera.close()
def getFrameTime(self):
"""
"""
return time.time() #current time epoch in secs.ms
def setResolution(self, (x, y)):
self.camera.resolution = (x, y)
def getResolution(self):
return self.camera.resolution
def isLastFrame(self):
"""
Added for compatibility with other cams
"""
return False
def hasSource(self):
"""
Is the camera active?
Return boolean
"""
return self.camera != None
def getImage(self):
"""
"""
frame = self.image_queue
if self.scale:
frame = cv2.resize( frame, self.resolution )
return frame, self.getFrameTime()
class realCam(Cam):
"""
a realCam class will handle a webcam connected to the system
camera is handled through cv2
"""
def __init__(self, devnum=0, resolution=(800, 600)):
self.devnum=devnum
self.resolution = resolution
self.scale = False
self.__initCamera()
def __initCamera(self):
"""
"""
self.camera = cv2.VideoCapture(self.devnum)
self.setResolution (self.resolution)
def getFrameTime(self):
"""
"""
return time.time() #current time epoch in secs.ms
def setResolution(self, (x, y)):
"""
Set resolution of the camera we are acquiring from
"""
x = int(x); y = int(y)
self.resolution = (x, y)
#http://stackoverflow.com/questions/11420748/setting-camera-parameters-in-opencv-python
self.camera.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, x)
self.camera.set(cv2.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):
"""
Return real resolution
"""
x1 = self.camera.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)
y1 = self.camera.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)
return (int(x1), int(y1))
def getImage( self ):
"""
Returns frame, timestamp
"""
if not self.camera:
self.__initCamera()
__, frame = self.camera.read()
try:
frame.shape > 0
except:
frame = self.getBlackFrame()
if self.scale:
frame = cv2.resize( frame, self.resolution )
return frame, self.getFrameTime()
def isLastFrame(self):
"""
Added for compatibility with other cams
"""
return False
def close(self):
"""
Closes the connection
http://stackoverflow.com/questions/15460706/opencv-cv2-in-python-videocapture-not-releasing-camera-after-deletion
"""
print "attempting to close stream"
self.camera.release
self.camera = None
def getSerialNumber(self):
"""
Uses pyUSB
http://stackoverflow.com/questions/8110310/simple-way-to-query-connected-usb-devices-info-in-python
http://askubuntu.com/questions/49910/how-to-distinguish-between-identical-usb-to-serial-adapters
"""
serial = 'NO_SERIAL'
plat = os.sys.platform # linux, linux2, darwin, win32
if "linux" in plat:
try:
addr = "/dev/video%s" % self.devnum
o = os.popen ("udevadm info %s | grep ID_SERIAL_SHORT" % addr).read().strip()
_ , serial = o.split("=")
except:
pass
return serial
def hasSource(self):
"""
Is the camera active?
Return boolean
"""
return self.camera.isOpened()
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):
"""
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 = cv2.VideoCapture(self.path)
#finding the input resolution
w = self.capture.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)
h = self.capture.get(cv2.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
def getResolution(self):
"""
Returns frame resolution as tuple (w,h)
"""
x = self.capture.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)
y = self.capture.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)
return (x,y)
def getFrameTime(self, asString=None):
"""
Return the time of the frame
"""
frameTime = self.capture.get(cv2.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):
"""
Returns frame, timestamp
"""
#cv2.SetCaptureProperty(self.capture, cv2.CV_CAP_PROP_POS_FRAMES, self.currentFrame)
# this does not work properly. Image is very corrupted
__, frame = self.capture.read()
try:
frame.shape > 0
except:
frame = self.getBlackFrame()
self.currentFrame += self.step
#elif self.currentFrame > self.lastFrame and not self.loop: return False
if self.scale:
frame = cv2.resize(frame, self.resolution)
return frame, self.getFrameTime()
def setResolution(self, w, h):
"""
Changes the output resolution
"""
self.resolution = (w, h)
self.scale = (self.resolution != self.in_resolution)
def getTotalFrames(self):
"""
Returns total number of frames
Be aware of this bug
https://code.ros.org/trac/opencv/ticket/851
"""
return self.capture.get( cv2.cv.CV_CAP_PROP_FRAME_COUNT )
def isLastFrame(self):
"""
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
def hasSource(self):
"""
Is the camera active?
Return boolean
"""
return self.capture.isOpened()
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):
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])
frame = cv2.imread(fp,cv2.CV_LOAD_IMAGE_COLOR)
self.in_resolution = frame.shape
if not resolution: resolution = self.in_resolution
self.resolution = resolution
self.scale = (self.in_resolution != self.resolution)
def getFrameTime(self, asString=None):
"""
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):
"""
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):
"""
Returns frame, timestamp
"""
n = self.currentFrame
fp = os.path.join(self.path, self.fileList[n])
self.currentFrame += 1
try:
frame = cv2.imread(fp,cv2.CV_LOAD_IMAGE_COLOR)
except:
print ( 'error with image %s' % fp )
raise
if self.scale:
frame = cv2.resize(frame, self.resolution)
self.last_time = self.getFrameTime()
return frame, self.last_time
def getTotalFrames(self):
"""
Return the total number of frames
"""
return self.totalFrames
def isLastFrame(self):
"""
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):
"""
Changes the output resolution
"""
self.resolution = (w, h)
self.scale = (self.resolution != self.in_resolution)
def getResolution(self):
"""
Return frame resolution
TODO: DOES THIS WORK?
"""
return self.resolution
def compressAllImages(self, compression=90, resolution=(960,720)):
"""
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
def hasSource(self):
"""
Is the camera active?
Return boolean
"""
return self.fileList != []
class ROImask():
"""
This is the Class handling the info about the ROI Mask
This classes adds and removes ROI, checks if a point is in ROI,
load and saves ROIS to file
No tracking here
"""
def __init__(self, parent):
self.monitor = parent
self.ROIS = [] #Regions of interest
self.beams = [] # beams: absolute coordinates
self.ROAS = [] #Regions of Action
self.points_to_track = []
self.referencePoints = ((),())
self.serial = None
def relativeBeams(self):
"""
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, ROIcoords):
"""
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) = ROIcoords
lx = min([x1,x2,x3,x4])
rx = max([x1,x2,x3,x4])
uy = min([y1,y2,y3,y4])
ly = max([y1,y2,y3,y4])
return ( (lx,uy), (rx, ly) )
def __distance( self, (x1, y1), (x2, y2) ):
"""
Calculate the distance between two cartesian points
"""
return np.sqrt((x2-x1)**2 + (y2-y1)**2)
def __getMidline (self, coords):
"""
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):
"""
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):
"""
Converts distance from pixels to cm
"""
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):
"""
Add a new ROI to the arena
"""
good_coords = (np.array(coords)>=0).all()
if good_coords:
self.ROIS.append( coords )
self.beams.append ( self.__getMidline (coords) )
self.points_to_track.append(n_flies)
def getROI(self, n):
"""
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):
"""
removes the nth crop area from the list
if n -1, remove all
"""
if n >= 0:
self.ROIS.pop(n)
self.beams.pop(n)
self.points_to_track.pop(n)
elif n < 0:
self.ROIS = []
self.beams = []
self.points_to_track = []
self.referencePoints == ((),())
def getROInumber(self):
"""
Return the number of current active ROIS
"""
return len(self.ROIS)
def saveROIS(self, filename, serial=None):
"""
Save the current crop data to a file
"""
print('saveROIS class ROIMask called')
cf = open(filename, 'w')
self.serial = serial
jsonData = {'ROIS':self.ROIS, 'pointsToTrack':self.points_to_track,'referencePoints': self.referencePoints, 'serial':self.serial}
json.dumps({self.ROIS, self.points_to_track, self.referencePoints, self.serial},cf)
cf.close()
def loadROIS(self, filename):
"""
Load the crop data from a file
"""
try:
cf = open(filename, 'r')
data = json.load(cf)
self.ROIS = []
tup=[]
for t in data['ROIS']:
for p in t:
p = tuple(p)
tup.append(p)
self.ROIS.append(tuple(tup))
tup=[]
self.points_to_track = data['pointsToTrack']
self.referencePoints = data['referencePoints']
if self.referencePoints == "none":
self.referencePoints = ((),())
if data['serial']=='NO_SERIAL':
self.serial = None
else:
self.serial = data['serial']
cf.close()
for coords in self.ROIS:
self.beams.append ( self.__getMidline (coords) )
return True
except:
return False
def resizeROIS(self, origSize, newSize):
"""
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 isPointInROI(self, pt):
"""
Check if a given point falls whithin one of the ROI
Returns the ROI number or else returns -1
"""
def __point_in_poly(pt, poly):
"""
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://opencv2.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 xrange(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
for ROI in self.ROIS:
if __point_in_poly(pt, ROI):
return self.ROIS.index(ROI)
return -1
def ROIStoRect(self):
"""
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 autoMask(self, pt1, pt2):
"""
EXPERIMENTAL, FIX THIS
This is experimental
For now it works only with one kind of arena
Should be more flexible than this
"""
rows = 16
cols = 2
food = .10
vials = rows * cols
ROI = [None,] * vials
(x, y), (x1, y1) = pt1, pt2
w, h = (x1-x), (y1-y)
d = h / rows
l = (w / cols) - int(food/2*w)
k = 0