-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenCVImageProcessingTools.py
2615 lines (2340 loc) · 129 KB
/
openCVImageProcessingTools.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
# import cv2
import sys
import pdb
import pickle
#from imutils import perspective
#from imutils import contours
import numpy as np
import pandas as pd
#import imutils
from scipy.spatial import distance as dist
from scipy import optimize
import math
import scipy
from scipy.interpolate import interp1d
from numpy.linalg import norm
import matplotlib.pyplot as plt
import matplotlib as mp
import os
import time
mp.use('TkAgg')
import tools.dataAnalysis as dataAnalysis
(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
import random
class openCVImageProcessingTools:
def __init__(self,analysisLoc, figureLoc, ff, showI = False):
# "/media/HDnyc_data/data_analysis/in_vivo_cerebellum_walking/LocoRungsData/170606_f37/170606_f37_2017.07.12_001_behavingMLI_000_raw_behavior.avi"
self.analysisLocation = analysisLoc
self.figureLocation = figureLoc
self.f = ff
self.showImages = showI
self.Vwidth = 816
self.Vheight = 616
self.testAboveBarGenerated = False
self.testBelowBarGenerated = False
############################################################
def __del__(self):
try :
self.video.release()
except:
pass
# cv2.destroyAllWindows()
print('on exit')
############################################################
def openVideo(self,pathAndFileName,outputProps=True):
# get properties
self.video = cv2.VideoCapture(pathAndFileName)
self.Vlength = int(self.video.get(cv2.CAP_PROP_FRAME_COUNT))
self.Vwidth = int(self.video.get(cv2.CAP_PROP_FRAME_WIDTH))
self.Vheight = int(self.video.get(cv2.CAP_PROP_FRAME_HEIGHT))
self.Vfps = self.video.get(cv2.CAP_PROP_FPS)
if outputProps:
print('Video properties : %s frames, %s pixels width, %s pixels height, %s fps' % (self.Vlength, self.Vwidth, self.Vheight, self.Vfps))
if not self.video.isOpened():
print('Could not open video')
sys.exit()
# read first video frame
ok, img = self.video.read()
if not ok:
print('Cannot read video file')
sys.exit()
# Return an array representing the indices of a grid.
self.imgGrid = np.indices((self.Vheight, self.Vwidth))
return (ok,img)
############################################################
def generateTestBarArray(self, yPos, areaWidth, location,shifts,recordingStruc=None,recordingBatch=None):
yLocation = yPos + areaWidth / 2.
#yRefBelow = self.Vheight - 0.899
#yRefAbove = self.Vheight - 381.119
print(yPos,yLocation,location,recordingStruc)
if recordingStruc is None:
yRefBelow = self.Vheight - 58.367
yRefAbove = self.Vheight - 257.599
polyCoeffsBelow = np.array([ 3.24055344e-08, -4.24100323e-05, 1.58473987e-02, 7.44691553e+01])#np.array([5.29427827e-10, -5.44334567e-07, 2.33618937e-04, -6.14393512e-02, 9.09112549e+01])
polyCoeffsAbove = np.array([-1.30470866e-08, 3.73803147e-05, -2.54318037e-02, 7.99139595e+01])#np.array([7.56895295e-10, -8.82197309e-07, 3.89379907e-04, -8.41450517e-02, 8.73406737e+01])
elif (recordingStruc == 'simplexBehavior') and (recordingBatch is None):
yRefBelow = self.Vheight - 86.242
yRefAbove = self.Vheight - 405.545
polyCoeffsBelow = np.array([ 5.77980631e-08, -5.77805502e-05, 1.21589718e-02, 8.34963092e+01])#np.array([-2.82445578e-10, 5.55470017e-07, -3.56808443e-04, 8.24484996e-02, 7.82924544e+01])
polyCoeffsAbove = np.array([ 2.04566542e-08, -5.48136664e-06, -8.77195245e-03, 8.04143685e+01]) #[-1.13037300e-10, 2.17339955e-07, -1.23679201e-04 , 1.95090152e-02, 7.82087407e+01]) #[-2.56275881e-10, 4.89392643e-07, -2.96872276e-04, 6.07987027e-02, 7.53825337e+01])
elif (recordingStruc == 'simplexBehavior') and (recordingBatch == 'B'):
yRefBelow = self.Vheight - 86.242
yRefAbove = self.Vheight - 405.545
polyCoeffsBelow = np.array([-7.07900126e-08, 1.18970766e-04, -5.69764360e-02, 1.01025512e+02]) #np.array([ 5.77980631e-08, -5.77805502e-05, 1.21589718e-02, 8.34963092e+01])#np.array([-2.82445578e-10, 5.55470017e-07, -3.56808443e-04, 8.24484996e-02, 7.82924544e+01])
polyCoeffsAbove = np.array([ 1.64889836e-08, 1.27960101e-05, -2.14594279e-02, 9.42392013e+01]) #np.array([ 2.04566542e-08, -5.48136664e-06, -8.77195245e-03, 8.04143685e+01]) #[-1.13037300e-10, 2.17339955e-07, -1.23679201e-04 , 1.95090152e-02, 7.82087407e+01]) #[-2.56275881e-10, 4.89392643e-07, -2.96872276e-04, 6.07987027e-02, 7.53825337e+01])
elif recordingStruc == 'simplexNew':
yRefBelow = self.Vheight - 141.13041968085105
yRefAbove = self.Vheight - 330.28578026595744
polyCoeffsBelow = np.array( [-1.00317930e-07, 1.55855102e-04, -7.48134828e-02, 9.13227764e+01])#np.array([ 1.00282581e-08, 6.00177385e-06, -1.18852681e-02, 9.13424242e+01]) # np.array([-2.82445578e-10, 5.55470017e-07, -3.56808443e-04, 8.24484996e-02, 7.82924544e+01])
polyCoeffsAbove = np.array([-5.34826974e-08, 8.25106659e-05, -3.87005977e-02, 8.57617865e+01])#np.array([ 5.94058018e-09, 1.93450068e-05, -2.25353790e-02, 9.15595770e+01]) # [-1.13037300e-10, 2.17339955e-07, -1.23679201e-04 , 1.950
#coeff4 = polyCoeffsBelow[4] + (yLocation - yRefBelow) * (polyCoeffsAbove[4] - polyCoeffsBelow[4]) / (yRefAbove - yRefBelow)
#if location == 'below':
# polyCoeffs = np.copy(polyCoeffsBelow)
#elif location == 'above':
# polyCoeffs = np.copy(polyCoeffsAbove)
#polyCoeffs[4] = coeff4
#print(yPos, yLocation, yRefBelow, yRefAbove, location, recordingStruc,polyCoeffs,coeff4)
testArray = np.zeros((shifts, self.Vwidth))
midBarArray = []
nRungs = []
for i in range(shifts):
# def generateBarArrayForTest(startIdx):
# testArray = np.zeros(self.Vwidth)
midBars = []
locIdx = i
nBars = 0
while ((locIdx + 18) < self.Vwidth) and nBars<9:
midBars.append(locIdx + 9)
testArray[i, (locIdx + 1):(locIdx + 3)] = np.array([0.33, 0.66])
testArray[i, (locIdx + 3):(locIdx + 16)] = 1.
testArray[i, (locIdx + 16):(locIdx + 18)] = np.array([0.66, 0.33])
distanceAbove = scipy.polyval(polyCoeffsAbove, locIdx)
distanceBelow = scipy.polyval(polyCoeffsBelow, locIdx)
distance = distanceBelow + (yLocation - yRefBelow)*(distanceAbove - distanceBelow)/(yRefAbove - yRefBelow)
#polyCoeffsBelow[4] + (yLocation - yRefBelow) * (polyCoeffsAbove[4] - polyCoeffsBelow[4]) / (yRefAbove - yRefBelow)
locIdx += int(distance + 0.5)
nBars+=1
midBarArray.append(midBars) # return(testArray,midBars)
nRungs.append(nBars)
return (testArray,midBarArray,nRungs)
############################################################
#self.findBarsDiffSum(imgGray, yPosAbove, barWidthAbove, loc='above', recStr=recStruc)
def findBarsDiffSum(self, firstImgGray, yPos, areaWidth, loc='above', recStr=None):
self.display = False
bestDiffSum = None
shifts = 100
#yLocation = yPos+areaWidth/2.
#yRefBelow = self.Vheight - 0.899
#yRefAbove = self.Vheight - 381.119
#polyCoeffsBelow = np.array([5.29427827e-10, -5.44334567e-07, 2.33618937e-04, -6.14393512e-02, 9.09112549e+01])
#polyCoeffsAbove = np.array([7.56895295e-10, -8.82197309e-07, 3.89379907e-04, -8.41450517e-02, 8.73406737e+01])
#coeff4 = polyCoeffsBelow[4] + (yLocation-yRefBelow)*(polyCoeffsAbove[4] - polyCoeffsBelow[4])/(yRefAbove-yRefBelow)
if loc == 'below':
if not self.testBelowBarGenerated :
(self.testArrayBelow,self.midBarArrayBelow) = self.generateTestBarArray( yPos, areaWidth, loc,shifts,recordingStruc=recStr)
#print('below test array generated')
self.testBelowBarGenerated = True
testArr = self.testArrayBelow
midBars = self.midBarArrayBelow
elif loc == 'above':
if not self.testAboveBarGenerated :
(self.testArrayAbove,self.midBarArrayAbove) = self.generateTestBarArray( yPos, areaWidth, loc,shifts,recordingStruc=recStr)
#print('above test array generated')
self.testAboveBarGenerated = True
testArr = self.testArrayAbove
midBars = self.midBarArrayAbove
nPoints = 100
intensity = np.log(np.average(firstImgGray[yPos:(yPos+areaWidth)],0))
differenceInt = np.abs(np.diff(intensity))
differenceIntConv = np.convolve(differenceInt,np.ones(6)/6,mode='same')
intensityConv = np.convolve(intensity,np.ones(nPoints)/nPoints,mode='same')
intensityAvgSub = np.abs(intensity - intensityConv) + np.concatenate((np.array([0]),differenceInt)) # + np.max(intensity)
# remove largest peak from array
idxPeak = np.argmax(intensityAvgSub)
intensityAvgSub[idxPeak-10:idxPeak+10]=0.
if loc == 'below':
intensityAvgSub[176:200] = 0
intensityAvgSub[176:200] = 0
shiftResults = []
for i in range(shifts):
#(testArr,midBars) = generateBarArrayForTest(i)
diffSum = np.sum(np.abs((intensityAvgSub - testArr[i]*max(intensityAvgSub)) ** 2))
if bestDiffSum is None or diffSum < bestDiffSum:
barLocs = midBars[i]
bestDiffSum = diffSum
#bestOffset = i
bestBarArray = testArr[i]
shiftResults.append([i,testArr,diffSum,midBars[i]])
#pdb.set_trace()
#print()
if self.display:
fig = plt.figure()
ax0 = fig.add_subplot(2,1,1)
ax0.plot(intensity)
ax0.plot(intensityAvgSub)
ax0.plot(intensityConv)
ax0.plot(bestBarArray*max(intensityAvgSub))
ax1 = fig.add_subplot(2,1,2)
for i in range(shifts):
ax1.plot(shiftResults[i][0],shiftResults[i][2],'o',c='C0')
plt.show()
pdb.set_trace()
return np.asarray(barLocs)
############################################################
############################################################
def videoToArray(self,videoFileName,limits=None):
# get properties
video = cv2.VideoCapture(videoFileName)
Vlength = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
Vwidth = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
Vheight = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
Vfps = video.get(cv2.CAP_PROP_FPS)
#if outputProps:
print('%s' % videoFileName)
print(' Video properties : %s frames, %s pixels width, %s pixels height, %s fps' % (Vlength, Vwidth, Vheight, Vfps))
if not video.isOpened():
print('Could not open video')
sys.exit()
if limits is None:
length = Vlength
includeBool = np.full(length, True)
else:
length = limits[1]-limits[0]
includeBool = np.full(Vlength, False)
includeBool[limits[0]:limits[1]] = True
frames = np.empty((length, Vwidth, Vheight))
#pdb.set_trace()
# read first video frame
nFrame = 0
nRead = 0
ok, img = video.read()
if not ok:
print('Cannot read video file')
sys.exit()
if includeBool[nRead]:
frames[nFrame] = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
nFrame+= 1
nRead+=1
while True:
ok, img = video.read()
if ok:
if includeBool[nRead]:
frames[nFrame] = np.transpose(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))
nFrame += 1
nRead+=1
else:
break
if nRead>limits[1]:
break
video.release()
print(nFrame, ' where added to array ')
return frames
############################################################
#self.findBarsDiffSum(imgGray, yPosAbove, barWidthAbove, loc='above', recStr=recStruc)
# (imgGray, yPosAbove, yPosBelow, barWidthBelow,rungPositions[-1],recStr=recStruc)
def findBarsDiffSumBoth(self, firstImgGray, yPosAbove, yPosBelow, areaWidth, lastRungPosition, recStr=None):
def getIntensityArray(img,yPos,loc):
intensity = np.log(np.average(img[yPos:(yPos + areaWidth)], 0))
differenceInt = np.abs(np.diff(intensity))
differenceIntConv = np.convolve(differenceInt, np.ones(4) / 4, mode='same')
intensityConv = np.convolve(intensity, np.ones(nPoints) / nPoints, mode='same')
intensityAvgSub = np.abs(intensity - intensityConv) + 5*np.concatenate((np.array([0]), differenceIntConv)) # + np.max(intensity)
# remove largest peak from array
# idxPeak = np.argmax(intensityAvgSub)
# intensityAvgSub[idxPeak-10:idxPeak+10]=0.
if loc == 'above':
intensityAvgSub[173:272] = 0
intensityAvgSub[272:317] = 0
elif loc == 'below': # because of the two vertical bar of the side-wall holder
intensityAvgSub[176:230] = 0
intensityAvgSub[273:322] = 0
intensityAvgSub[:43] = 0
intensityAvgSub[-43:] = 0
return intensityAvgSub
self.display = False
bestDiffSumAbove = None
bestDiffSumBelow = None
shifts = 100
#yLocation = yPos+areaWidth/2.
#yRefBelow = self.Vheight - 0.899
#yRefAbove = self.Vheight - 381.119
#polyCoeffsBelow = np.array([5.29427827e-10, -5.44334567e-07, 2.33618937e-04, -6.14393512e-02, 9.09112549e+01])
#polyCoeffsAbove = np.array([7.56895295e-10, -8.82197309e-07, 3.89379907e-04, -8.41450517e-02, 8.73406737e+01])
#coeff4 = polyCoeffsBelow[4] + (yLocation-yRefBelow)*(polyCoeffsAbove[4] - polyCoeffsBelow[4])/(yRefAbove-yRefBelow)
if not self.testBelowBarGenerated :
(self.testArrayBelow,self.midBarArrayBelow,self.nRungs) = self.generateTestBarArray( yPosBelow, areaWidth, 'below',shifts,recordingStruc=recStr)
#print('below test array generated')
self.testBelowBarGenerated = True
testArrBelow = self.testArrayBelow
midBarsBelow = self.midBarArrayBelow
numberOfRungsBelow = self.nRungs
#elif loc == 'above':
if not self.testAboveBarGenerated :
(self.testArrayAbove,self.midBarArrayAbove,self.nRungs) = self.generateTestBarArray( yPosAbove, areaWidth, 'above',shifts,recordingStruc=recStr)
#print('above test array generated')
self.testAboveBarGenerated = True
testArrAbove = self.testArrayAbove
midBarsAbove = self.midBarArrayAbove
numberOfRungsAbove = self.nRungs
nPoints = 100
intensityAvgSubBelow = getIntensityArray(firstImgGray,yPosBelow,'below')
intensityAvgSubAbove = getIntensityArray(firstImgGray, yPosAbove, 'above')
shiftResults = []
for i in range(shifts):
#(testArr,midBars) = generateBarArrayForTest(i)
diffSumAbove = np.sum(((intensityAvgSubAbove - testArrAbove[i]*max(intensityAvgSubAbove)) ** 2))
if bestDiffSumAbove is None or diffSumAbove < bestDiffSumAbove:
barLocsAbove = midBarsAbove[i]
bestShiftAbove = i
bestDiffSumAbove = diffSumAbove
#bestOffset = i
bestBarArrayAbove = testArrAbove[i]
for i in range(bestShiftAbove-30,((bestShiftAbove+30) if (bestShiftAbove+30)<100 else 99)):
diffSumBelow = np.sum(((intensityAvgSubBelow - testArrBelow[i] * max(intensityAvgSubBelow)) ** 2))
if bestDiffSumBelow is None or diffSumBelow < bestDiffSumBelow:
barLocsBelow = midBarsBelow[i]
bestShiftBelow = i
bestDiffSumBelow = diffSumBelow
#bestOffset = i
bestBarArrayBelow = testArrBelow[i]
shiftResults.append([i,testArrAbove[i],testArrBelow[i],intensityAvgSubAbove,intensityAvgSubBelow,diffSumAbove,diffSumBelow,diffSumBelow,midBarsAbove[i],midBarsBelow[i]])
#print(bestShiftAbove,bestShiftBelow,(bestShiftAbove-bestShiftBelow),barLocsAbove,barLocsBelow)
#pdb.set_trace()
#print()
if self.display:
mp.use('WxAgg')
fig = plt.figure()
ax0 = fig.add_subplot(2,2,1)
#ax0.plot(intensity)
ax0.plot(intensityAvgSubAbove)
#ax0.plot(intensityConv)
ax0.plot(shiftResults[bestShiftAbove-2][1]*max(intensityAvgSubAbove),lw=0.5,c='green')
ax0.plot(bestBarArrayAbove*max(intensityAvgSubAbove))
ax0.plot(shiftResults[bestShiftAbove+2][1]*max(intensityAvgSubAbove),lw=0.5, c='red')
ax1 = fig.add_subplot(2,2,2)
for i in range(shifts):
ax1.plot(shiftResults[i][0],shiftResults[i][5],'o',c='C0')
ax2 = fig.add_subplot(2,2,3)
#ax0.plot(intensity)
ax2.plot(intensityAvgSubBelow)
#ax0.plot(intensityConv)
ax2.plot(bestBarArrayBelow*max(intensityAvgSubBelow))
ax3 = fig.add_subplot(2,2,4)
for i in range(shifts):
ax3.plot(shiftResults[i][0],shiftResults[i][6],'o',c='C0')
plt.show()
pdb.set_trace()
return (np.asarray(barLocsAbove),np.asarray(barLocsBelow),bestShiftAbove,bestShiftBelow)
############################################################
def findBarsCrossCorr(self, firstImgGray, yPos, areaWidth, location):
self.display = False
yLocation = int(yPos + areaWidth / 2.)
if location == 'below':
polyCoeffs = np.array([ 5.29427827e-10, -5.44334567e-07, 2.33618937e-04, -6.14393512e-02, 9.09112549e+01])
elif location == 'above':
polyCoeffs = np.array([ 7.56895295e-10, -8.82197309e-07, 3.89379907e-04, -8.41450517e-02, 8.73406737e+01])
barWidth = 15
testArray = np.zeros(self.Vwidth)
locIdx = 0
while locIdx<self.Vwidth:
testArray[(locIdx+1):(locIdx+3)] = np.array([0.33,0.66])
testArray[(locIdx+3):(locIdx+16)] = 1.
testArray[(locIdx+16):(locIdx+18)] = np.array([0.66,0.33])
distance = scipy.polyval(polyCoeffs, locIdx)
locIdx += int(distance+0.5)
intensity = np.log(np.average(firstImgGray[yPos:(yPos+areaWidth)],0))
#intensityBelow = np.average(firstImgGray[yPosBelow:(yPosBelow+barWidthBelow)],0)
corrBars = dataAnalysis.crosscorr(1,intensity,testArray,100)
maximaIdx = scipy.signal.argrelextrema(corrBars[:,1],np.greater)
#minimaIdx = scipy.signal.argrelextrema(corrBars[:,1],np.less)
maximaLocations = corrBars[:, 0][maximaIdx[0]].astype(int)
maxima = corrBars[:, 1][maximaIdx[0]]
maximum = np.max(maxima)
maximumLoc = maximaLocations[np.argmax(maxima)]
#loc = np.argmax(corrBars[:, 1][maximaIdx[0]].astype(int))
barLocation = []
if maximumLoc < 0:
bL = maximumLoc#+9
elif maximumLoc >= 0:
bL = (-maximumLoc)
barLocation.append(bL)
while barLocation[-1]<self.Vwidth:
distance = scipy.polyval(polyCoeffs, barLocation[-1])
nL = distance + barLocation[-1]
barLocation.append(nL)
barLocation=np.asarray(barLocation)
#print(maximaStats)
#pdb.set_trace()
#print()
if self.display:
fig = plt.figure()
ax0 = fig.add_subplot(2,1,1)
ax0.plot(intensity)
for i in maximaLocations:
x = np.arange(len(testArray))
y = testArray
if i < 0:
x = x[abs(i):]
y = y[:-abs(i)]
elif i >= 0:
x = x[:-abs(i)]
y = y[abs(i):]
ax0.plot(x,y*max(intensity),label='%s, %s' % (i,i))
plt.legend()
ax1 = fig.add_subplot(2,1,2)
ax1.plot(corrBars[:,0],corrBars[:,1])
plt.show()
pdb.set_trace()
return barLocation
############################################################
def findHorizontalArea(self, img, coordinates=None,orientation='horizontal'):
if coordinates is None:
pos = 300
areaWidth = 10
else:
pos = coordinates[0]
areaWidth = coordinates[1]
Npix = 5
continueLoop = True
# optimize with keyboard
while continueLoop:
#rungs = []
imgLine = img.copy()
if orientation=='horizontal':
cv2.line(imgLine, (0, pos), (self.Vwidth, pos), (255, 0, 255), 2)
cv2.line(imgLine, (0, pos+areaWidth), (self.Vwidth, pos+areaWidth), (255, 0, 255), 2)
elif orientation == 'vertical':
cv2.line(imgLine, (pos, 0), (pos, self.Vheight), (255, 0, 255), 2)
cv2.line(imgLine, (pos+areaWidth, 0), (pos+areaWidth, self.Vheight), (255, 0, 255), 2)
cv2.imshow("Rungs", imgLine)
#print 'current xPosition, yPostion : ', xPosition, yPosition
PressedKey = cv2.waitKey(0)
if PressedKey == 56 or PressedKey ==82: #UP arrow
pos -= Npix
elif PressedKey == 50 or PressedKey ==84: #DOWN arrow
pos += Npix
elif PressedKey == 54 or PressedKey ==83: #RIGHT arrow
areaWidth += Npix
elif PressedKey == 52 or PressedKey ==81: #LEFT arrow
areaWidth -= Npix
elif PressedKey == 13 or PressedKey == 32: # Enter or Space
continueLoop = False
elif PressedKey == 27: # Escape
continueLoop = False
else:
pass
cv2.destroyWindow("Rungs")
if orientation == 'horizontal':
print('y Pos, width :', pos,areaWidth)
elif orientation == 'vertical':
print('x Pos, width :', pos,areaWidth)
#mask = np.zeros((self.Vheight, self.Vwidth))
return (pos,areaWidth)
############################################################
# (frames,coordinates=SavedLEDcoordinates,currentCoordExist=currentCoodinatesExist)
def findLEDNumberArea(self, frames, coordinates=None, currentCoordExist=False, determineAgain=False, videoType=None, auto=False):
if videoType is None:
initialValues = [730,30,20, 43,20]
typicalLEDnumber = True
elif videoType == 'GigEAnimalBonsai':
initialValues = [712, 27, 19,43,16]
typicalLEDnumber = True
elif videoType == 'Cham3WhiskerBonsai':
initialValues = [529, 409, 28, 66,-6]
typicalLEDnumber = True
# auxilary functions
mp.use('TkAgg')
# pdb.set_trace()
if type(frames)==np.ndarray : # contains the actual raw frames
avgFrame = np.average(frames[5000:6000], axis=0)
elif type(frames) == str: # contains the pointer to the frame stream
videoFrames = self.videoToArray(frames,limits=[5000,5200])
avgFrame = np.average(videoFrames, axis=0)
#cv2.imwrite('image_%s.png' % videoType, np.transpose(avgFrame), [cv2.IMWRITE_PNG_COMPRESSION, 1])
def detect_circles(img):
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Set minimum and maximum circle sizes
min_radius = 3
max_radius = 50
# Set minimum distance between circle centers
min_distance = round(9)
# Set the number of circles expected to be found
num_circles = 4
# Initialize the list to store the detected circles
circles_list = []
breakout = False
mask = np.zeros(gray.shape, dtype=np.uint8)
mask[0:120, 667:790] = 255
masked_gray = cv2.bitwise_and(gray, mask)
max_guess_accumulator_array_threshold = 100
guess_accumulator_array_threshold = max_guess_accumulator_array_threshold
# Loop over different parameters to detect circles
while guess_accumulator_array_threshold > 1 and breakout == False:
circles = cv2.HoughCircles(masked_gray,
cv2.HOUGH_GRADIENT,
dp=1, # resolution of accumulator array.
minDist=45,
# number of pixels center of circles should be from each other, hardcode
param1=16,
param2=guess_accumulator_array_threshold,
# minRadius=guess_radius - 1,
minRadius=13,
# HoughCircles will look for circles at minimum this size
maxRadius=35,
# HoughCircles will look for circles at maximum this size
)
if circles is not None:
if len(circles[0]) == num_circles:
circles_list.append(circles)
print('good circles found !!!!!!!!')
g=0
for c in range(4):
if (circles[0][c][1]<120) and (circles[0][c][0]>650):
g+=1
guess_accumulator_array_threshold -= 1
# for (x, y, r) in cir:
random_index = random.randint(0, len(circles_list) - 1)
cir=circles_list[random_index]
# convert the (x, y) coordinates and radius of the circles to integers
output = np.copy(img)
print(cir[0, :])
cir = np.round(cir[0, :]).astype("int")
cirSum=np.sum(cir, axis=1)
order=np.argsort(cirSum)
orderedCir=cir[order]
print('auto circle', orderedCir)
# for (x, y, r) in cir:
# # pdb.set_trace()
# cv2.circle(output, (x, y), r, (0, 0, 255), 2)
# # cv2.circle(output, (x, y), r, (0, 255, 255), 10)
# cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
# cv2.imshow("output", np.hstack([img, output]))
# cv2.imshow("output", output)
# # cv2.waitKey(0).hstack([imgList[i], output])
# cv2.waitKey(0)
# # pdb.set_trace()
LEDcoordinates=[4,orderedCir[:,0], orderedCir[:,1], 18]
return LEDcoordinates
def rotatePoints(theta,x,y):
x = x.astype(float)
y = y.astype(float)
posXTemp = x[1:] - x[0] # move the rotation point to the origin
posYTemp = y[1:] - y[0] # move the rotation point to the origin
rotMatrix = np.array([[np.cos(theta*np.pi/180.), -np.sin(theta*np.pi/180.)], [np.sin(theta*np.pi/180.), np.cos(theta*np.pi/180.)]])
posRotTemp = np.matmul(rotMatrix, np.row_stack((posXTemp, posYTemp)))
#print('before')
#pdb.set_trace()
#posRotTemp = (posRotTemp+0.5).astype(int)
x[1:] = posRotTemp[0] + x[0]
y[1:] = posRotTemp[1] + y[0]
#print('after')
#pdb.set_trace()
return (x,y) # 0.5 is added to get the correct rounding
def changeSpacing(nLED,spacing,x,y):
for i in range(1, nLED):
x[i] = x[0] + (i % 2) * spacing
y[i] = y[0] + (i // 2) * spacing
return (x,y)
##############################
if determineAgain:
doLEDROIdetermination = True
else:
doLEDROIdetermination = (not currentCoordExist)
# don't check location if recording already exists
if doLEDROIdetermination :
#pdb.set_trace()
# the below in the clause allows to set the ROI on the LED location
frame8bit = np.array(np.transpose(avgFrame), dtype=np.uint8)
img = cv2.cvtColor(frame8bit, cv2.COLOR_GRAY2BGR)
cv2.imwrite('averageImg.jpg', img)
if auto:
coordinates=detect_circles(img)
nLED = coordinates[0]
posX = coordinates[1]
posY = coordinates[2]
circleRadius=coordinates[3]
continueCountLEDLoop = True
# while continueCountLEDLoop:
imgCircle = img.copy()
for i in range(nLED):
cv2.circle(imgCircle, (int(posX[i]+0.5), int(posY[i]+0.5)), circleRadius, (255, 0, 255), 2)
cv2.putText(imgCircle,'%s' % i, (int(posX[i]+0.5), int(posY[i]+0.5)), fontFace=cv2.FONT_HERSHEY_DUPLEX, thickness=1, fontScale=0.6,color=(255,0,0))
cv2.imshow("ImageWithLEDCircles", imgCircle)
cv2.waitKey(2000) # Wait for 2000 milliseconds (2 seconds)
cv2.destroyWindow("ImageWithLEDCircles")
cv2.destroyAllWindows()
else:
# first let's decide on how many LED's (if any) are present in the FOV
if (coordinates is None) and (not typicalLEDnumber):
continueCountLEDLoop = True
while continueCountLEDLoop:
#rungs = []
imgPure = img.copy()
cv2.imshow("PureImage", imgPure)
print('specify how many LEDs are present in the field of view (e.g., 1,4 or 0 if none) :')
PressedKey = cv2.waitKey(0)
print(PressedKey)
if PressedKey == 49:
nLED = 1
elif PressedKey == 52 :
nLED = 4
elif PressedKey == 48:
nLED = 0
try:
print('Number of LEDs in image :',nLED)
except:
pass
else:
continueCountLEDLoop = False
cv2.destroyWindow("PureImage")
elif (coordinates is None) and typicalLEDnumber:
nLED = 4
else:
nLED = coordinates[0]
## sets the location of the ROIs for all LEDs
if nLED > 0:
movePixels = 1
#spacing = 50
rotAngle = 2.
continueLoop = True
# optimize with keyboard
if (coordinates is None) or any(coordinates[1]>800) or any(coordinates[2]>800):
posX = np.full(nLED,0)
posY = np.full(nLED,0)
posX[0] = initialValues[0] # 730
posY[0] = initialValues[1] # 30
circleRadius = initialValues[2] #20
spacing = initialValues[3]
theta = initialValues[4]
(posX,posY) = changeSpacing(nLED,spacing,posX,posY)
(posX,posY) = rotatePoints(theta,posX,posY)
else:
nLED = coordinates[0]
posX = coordinates[1]
posY = coordinates[2]
circleRadius = coordinates[3]
spacing = coordinates[4]
theta = coordinates[5]
#(posX, posY) = changeSpacing(nLED, spacing, posX, posY)
#(posX, posY) = rotatePoints(theta, posX, posY)
print(posX,posY)
while continueLoop:
#rungs = []
imgCircle = img.copy()
for i in range(nLED):
cv2.circle(imgCircle, (int(posX[i]+0.5), int(posY[i]+0.5)), circleRadius, (255, 0, 255), 2)
cv2.putText(imgCircle,'%s' % i, (int(posX[i]+0.5), int(posY[i]+0.5)), fontFace=cv2.FONT_HERSHEY_DUPLEX, thickness=1, fontScale=0.6,color=(255,0,0))
cv2.imshow("ImageWithLEDCircles", imgCircle)
print('change circle position with arrow buttons; circle size with + or - buttons; rotation with r, l button; spacing with w,c buttons; exit loop with space/enter or ESC :')
PressedKey = cv2.waitKey(0)
print(PressedKey)
print(posX,posY,circleRadius,spacing,theta)
if PressedKey == 56 or PressedKey ==82: #UP arrow
posY -= movePixels
elif PressedKey == 50 or PressedKey ==84: #DOWN arrow
posY += movePixels
elif PressedKey == 54 or PressedKey ==83: #RIGHT arrow
posX += movePixels
elif PressedKey == 52 or PressedKey ==81: #LEFT arrow
posX -= movePixels
elif PressedKey == 61 : #+ button
circleRadius += movePixels
elif PressedKey == 45 : #- button
circleRadius -= movePixels
elif PressedKey == 114 : # r button
theta += rotAngle
(posX,posY) = rotatePoints(rotAngle,posX,posY)
elif PressedKey == 108 : # l button
theta -=rotAngle
(posX, posY) = rotatePoints(-rotAngle, posX, posY)
elif PressedKey == 119 : # w button
spacing +=movePixels
(posX,posY) = changeSpacing(nLED,spacing,posX,posY)
elif PressedKey == 99 : # c button
spacing -=movePixels
(posX, posY) = changeSpacing(nLED,spacing, posX, posY)
elif PressedKey == 13 or PressedKey == 32: # Enter or Space
continueLoop = False
elif PressedKey == 27: # Escape
continueLoop = False
else:
pass
cv2.destroyWindow("ImageWithLEDCircles")
print('LED positions : ',posX,posY,circleRadius,spacing,theta)
else:
print('No LED in field of view.')
posX = None
posY = None
circleRadius = None
else:
if not auto:
(nLEDs,posX,posY,circleRadius,spacing,theta) = (coordinates[0],coordinates[1],coordinates[2],coordinates[3],coordinates[4],coordinates[5])
else:
(nLEDs, posX, posY, circleRadius) = (
coordinates[0], coordinates[1], coordinates[2], coordinates[3])
if not auto:
print('coordinates used for extraction :',nLED,posX,posY,circleRadius,spacing,theta)
coordinates = np.array([nLED, posX, posY, circleRadius, spacing, theta], dtype=object)
else:
print('coordinates used for extraction :',nLED,posX,posY,circleRadius)
coordinates = np.array([nLED, posX, posY, circleRadius], dtype=object)
return coordinates
############################################################
# extract temporal trace of LED area mask
def extractLEDtraces(self, frames, coordinates, videoId,optimize=False):
(nLEDs, posX, posY, circleRadius) = (coordinates[0], coordinates[1], coordinates[2], coordinates[3])
LEDtraces = []
if type(frames) == np.ndarray:
# get mask for circular area comprising the LED
dims = np.shape(np.transpose(frames[0]))
maskGrid = np.indices((dims[0],dims[1]))
framesNew = np.transpose(frames, axes=(0, 2, 1)) # permutate last two axes as for the image depiction
for i in range(nLEDs):
maskCircle = np.sqrt((maskGrid[1] - posX[i]) ** 2 + (maskGrid[0] - posY[i]) ** 2) < circleRadius
# apply mask to the frame array and extract mean brigthness of the LED ROI
LEDtr = np.mean(framesNew[:,maskCircle],axis=1)
LEDtraces.append(LEDtr)
# print('LED number', i)
plt.plot(LEDtr)
plt.show()
elif type(frames) == str:
def getValuesBasedOnMask(frame,posX,posY, optimize):
vals = []
for i in range(nLEDs):
maskCircle = np.sqrt((maskGrid[1] - posX[i])**2 + (maskGrid[0] - posY[i])**2) < circleRadius*0.3
vals.append(np.mean(frame[maskCircle]))
return vals
#video = frames
video = cv2.VideoCapture(frames)
Vlength = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
Vwidth = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
Vheight = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
Vfps = video.get(cv2.CAP_PROP_FPS)
#if outputProps:
print(' Video properties : %s frames, %s pixels width, %s pixels height, %s fps' % (Vlength, Vwidth, Vheight, Vfps))
maskGrid = np.indices((Vheight,Vwidth))
# read first video frame
LEDtraces = []
if optimize:
####################################################################################\
# Read a few test frames to find the optimal mask position
videoTest = cv2.VideoCapture(frames)
num_test_frames=60
test_frames = []
frame_count=0
total_frames = int(videoTest.get(cv2.CAP_PROP_FRAME_COUNT))
random_divisor = random.randint(2, 7)
start_frame = (total_frames - num_test_frames) // random_divisor # Calculate the starting frame index
print(f'lets take frame {start_frame} - {start_frame+num_test_frames} for optimization...')
videoTest.set(cv2.CAP_PROP_POS_FRAMES, start_frame) # Set the video capture to the starting frame
for _ in range(num_test_frames):
okTest, imgTest = videoTest.read()
if okTest:
gray_frameTest = cv2.cvtColor(imgTest, cv2.COLOR_BGR2GRAY)
test_frames.append(gray_frameTest)
frame_count += 1
progress = frame_count / num_test_frames * 100 # Calculate the loading progress percentage
sys.stdout.write('\r')
sys.stdout.write(f'Loading test frames: {frame_count}/{num_test_frames} - {progress:.2f}% complete')
sys.stdout.flush()
optimal_mask_positions = []
print('\nTest frames loaded')
print('\nSearching for the optimal mask position')
start_timeMask = time.time()
# Find the optimal mask position for each LED based on luminosity differences
# for i in range(nLEDs):
# luminosity_diff = np.zeros((2 * circleRadius + 1, 2 * circleRadius + 1))
# for x in range(int(posX[i]) - circleRadius, int(posX[i]) + circleRadius + 1):
# for y in range(int(posY[i]) - circleRadius, int(posY[i]) + circleRadius + 1):
# if 0 <= x < Vwidth and 0 <= y < Vheight:
# maskCircle = np.sqrt((maskGrid[1] - x) ** 2 + (maskGrid[0] - y) ** 2) < circleRadius
# LED_luminosity = np.array([np.mean(frame[maskCircle]) for frame in test_frames])
# luminosity_diff[x - int(posX[i]) + circleRadius, y - int(posY[i]) + circleRadius] = np.max(LED_luminosity) - np.min(LED_luminosity)
#
# # Find the pixel with the maximum luminosity difference
# best_pixel_idx = np.unravel_index(np.argmax(luminosity_diff), luminosity_diff.shape)
# best_x = best_pixel_idx[0] + int(posX[i]) - circleRadius
# best_y = best_pixel_idx[1] + int(posY[i]) - circleRadius
# optimal_mask_positions.append((best_x, best_y))
# print('\noptimal mask position found')
for i in range(nLEDs):
max_luminosity_diff = 0
optimal_x = None
optimal_y = None
compareFrameIdx = 12 # Use luminosity differences across 7 consecutive frames
for x in range(int(posX[i]) - circleRadius, int(posX[i]) + circleRadius + 1):
for y in range(int(posY[i]) - circleRadius, int(posY[i]) + circleRadius + 1):
elapsed_timeMask = time.time() - start_timeMask
sys.stdout.write('\r')
sys.stdout.write(
f'Elapsed Time: {elapsed_timeMask:.2f} s | {elapsed_timeMask / 110 * 100:.2f}% complete ')
sys.stdout.flush()
if 0 <= x < Vwidth and 0 <= y < Vheight:
maskCircle = np.sqrt((maskGrid[1] - x) ** 2 + (maskGrid[0] - y) ** 2) < circleRadius
# Calculate luminosity differences across compareFrameIdx consecutive frames
luminosity_diff_frames = [
np.abs(np.mean(frame[maskCircle]) - np.mean(prev_frame[maskCircle])) for
frame, prev_frame in
zip(test_frames[compareFrameIdx:], test_frames[:-compareFrameIdx])]
max_diff = max(luminosity_diff_frames)
if max_diff > max_luminosity_diff:
max_luminosity_diff = max_diff
optimal_x = x
optimal_y = y
optimal_mask_positions.append((optimal_x, optimal_y))
# Continue with processing frames using the optimal mask positions
frame_count = 0
start_time = time.time()
print('\nextracting LED traces...')
while True:
ok, img = video.read()
if ok:
gray_frame = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
LED_vals = getValuesBasedOnMask(gray_frame, [pos[0] for pos in optimal_mask_positions],
[pos[1] for pos in optimal_mask_positions], optimize)
frame_count += 1
progress = (frame_count / Vlength * 100) # Calculate the loading progress percentage
elapsed_time = time.time() - start_time
# Calculate remaining time
remaining_frames = Vlength - frame_count
frames_per_second = frame_count / elapsed_time
estimated_remaining_time = remaining_frames / frames_per_second
sys.stdout.write('\r')
sys.stdout.write(f'{videoId} | Loading frames: {frame_count}/{Vlength} - {progress:.2f}% complete | Elapsed Time: {elapsed_time:.2f} s | Estimated Remaining Time: {estimated_remaining_time:.2f} s')
sys.stdout.flush()
LEDtraces.append(LED_vals)
# Display the frame with optimal masks for one second
if frame_count==200:
for pos in optimal_mask_positions:
x, y = pos
maskCircle = np.sqrt((maskGrid[1] - x) ** 2 + (maskGrid[0] - y) ** 2) < circleRadius*0.3
img[maskCircle] = [0, 0,
255] # Set mask area to red color (you can adjust the color as needed)
cv2.imshow("Optimal Mask Frame", img)
cv2.waitKey(5000) # Display for 1 second
cv2.destroyAllWindows()
# ok, img = video.read()
else:
print('breaking at nFrame : ', frame_count)
break
print(' extracted LED values for %s frames' % len(LEDtraces))
# Convert the LEDtraces list to a NumPy array and transpose it
LEDtraces = np.transpose(np.asarray(LEDtraces))
video.release()
print('LED traces extracted')
else:
##################################################
ok, img = video.read()
LEDtraces.append(getValuesBasedOnMask(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY),posX,posY, optimize))
nFrame = 1
start_time = time.time()
while True:
ok, img = video.read()
if ok:
LEDtraces.append(getValuesBasedOnMask(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY),posX,posY, optimize))
nFrame += 1
progress = (nFrame / Vlength * 100) # Calculate the loading progress percentage
elapsed_time = time.time() - start_time
# Calculate remaining time
remaining_frames = Vlength - nFrame
frames_per_second = nFrame / elapsed_time
estimated_remaining_time = remaining_frames / frames_per_second
sys.stdout.write('\r')
sys.stdout.write(f'{videoId} |Loading frames: {nFrame}/{Vlength} - {progress:.2f}% complete | Elapsed Time: {elapsed_time:.2f} s | Estimated Remaining Time: {estimated_remaining_time:.2f} s')
sys.stdout.flush()
else:
print('breaking at nFrame : ', nFrame)
break
print(' extracted LED values for %s frames' % nFrame)
if nFrame != Vlength:
print('Discrepancy : video length and extracted ROI values do not match!')
pdb.set_trace()
LEDtraces = np.transpose(np.asarray(LEDtraces))
video.release()
print('LED traces extracted')
return (LEDtraces)
############################################################
# if verbose:
# for i in range(4):
# # print('LED number', i)
# plt.plot(LEDtraces, alpha=0.4)
#
# plt.show()
############################################################
def extractFramesFromVideoFile(self,fileName):
video = cv2.VideoCapture(fileName)
Vlength = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
Vwidth = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
Vheight = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
Vfps = video.get(cv2.CAP_PROP_FPS)
# if outputProps:
print(' Video properties : %s frames, %s pixels width, %s pixels height, %s fps' % (Vlength, Vwidth, Vheight, Vfps))
#maskGrid = np.indices((Vheight, Vwidth))
# read first video frame
frames = np.empty((Vlength,Vheight,Vwidth),dtype=np.uint8)
ok, img = video.read()
frames[0] = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#LEDtraces.append(getValuesBasedOnMask(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), posX, posY))
nFrame = 1
while True:
ok, img = video.read()
if ok:
frames[nFrame]=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
nFrame += 1
else:
print('breaking at nFrame : ', nFrame)
break
print(' generated numpy array for %s frames' % nFrame)
if nFrame != Vlength:
print('Discrepancy : video length and extracted ROI values do not match!')
pdb.set_trace()
video.release()
return frames
############################################################
def cropImg(self, img,Ycoordinates=None):