forked from AutomaticBehaviorRecognitionSystem/ABRS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
video_to_ST3C_image_batch_AER.py
268 lines (181 loc) · 11.3 KB
/
video_to_ST3C_image_batch_AER.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2019 Primoz Ravbar UCSB
# Licensed under BSD 2-Clause [see LICENSE for details]
# Written by Primoz Ravbar
"""
Modified on Sat Oct 5 10:02:58 2019
@author: Augusto Escalante
"""
import numpy as np
import pickle
import os
import platform
import tensorflow as tf
from tensorflow import keras
from ABRS_modules import getting_frame_record
from ABRS_modules import read_frames
from ABRS_modules import create_3C_image
OSplatform = platform.system()
###############################################################
#Parameters set by the user
###############################################################
frameRate = 30;
#Number of frames in one clip
clipStart = 0;
clipEnd = 99
bufferSize = 50;
clipsNumberMax = 1; #
#Size to which resize the original video (if equal to the longest dimension,
#no resizing will take place (no resizing will result in slower processing
#and apparently there is no resolution advantage given the final resizing to 80)):
newSize = [400,400];
#Desired roi size around subject of interest (must be pair) = subarea of the original frame:
roi = 80;
#Desired final image size for training the Convolutional Neural Network:
CVNsize = 80;
#Number of frames to calculate the higher scale spatiotemporal feature (red channel):
windowST = 15; #~=0.5 seconds at 30 fps
# windowST = 10; #~=0.33 seconds at 30 fps
# windowST = 20; #~=0.66 seconds at 30 fps
# windowST = 30; #=1 second at 30 fps
#fbList = [1,2,3,4]; # works for raw movies with 2x2 arenas (split the frames into 4)
#fbList = [1]; # one arena in the frame #AER: it will still subdivide the arena and take just the upper left square because of function getting_frame_record
fbList = [0];
clipFirst = 0;
firstFolder = 0;
# select a ConvNet model to recognize the behavior from the ST-images; behavior labels will be stored; select 'none' for no model
modelName = 'none' # use 'none' or the name in the model (must be in the ABRS folder)
#modelName = 'modelConv2ABRS_3C_train_with_labelCS1fb1_SS_plus_LiManualLabel'
if OSplatform == 'Linux':
# rawVidDirPath = '/home/augustoer/ABRS/Test'; #lab path
rawVidDirPath = '/home/auesro/Desktop/ABRS/Test'; #home path
# rawVidDirPath = '/home/auesro/Desktop/ABRS Test'; #logitech
# dirPathOutput = '/home/augustoer/ABRS'; #ST-images and other data will be stored here
dirPathOutput = '/home/auesro/Desktop/ABRS'; #home path
# if OSplatform == 'Windows':
# rawVidDirPath = 'INSERT ROW VIDEO FOLDER PATH';
# dirPathOutput = 'INSERT THE OUTPUT FOLDER PATH'; #ST-images and other data will be stored here
# if OSplatform == 'Darwin':
# rawVidDirPath = 'INSERT ROW VIDEO FOLDER PATH';
# dirPathOutput = 'INSERT THE OUTPUT FOLDER PATH'; #ST-images and other data will be stored here
##################################################################
def video_clips_to_3C_image_fun (dirPathInput,dirPathOutput,fbList,clipStart,clipEnd,clipsNumber,bufferSize,windowST,modelName,OSplatform,roi,CVNsize):
if modelName != 'none':
model = keras.models.load_model(modelName)
clips = np.arange(clipFirst,clipsNumber,1);
fileList = os.listdir(dirPathInput);
clIndex = 0;
for cl in clips:
fileName = fileList[cl];
ext = fileName[-3:];
if (ext == 'avi' or ext == 'mov' or ext == 'mp4') == True:
if OSplatform == 'Linux':
fileDirPathInputName = dirPathInput + '/' + fileName;
if OSplatform == 'Windows':
fileDirPathInputName = dirPathInput + '\\' + fileName;
if OSplatform == 'Darwin':
fileDirPathInputName = dirPathInput + '/' + fileName;
r = np.arange(0,clipEnd,bufferSize)
for bf in r:
startFrame = bf;
endFrame = startFrame + bufferSize;
frRec = read_frames(startFrame, endFrame, fileDirPathInputName, newSize) #resizes frame to newSize
if clIndex == clips[0] and startFrame == clipStart:
frRecRemain = np.zeros((windowST,(int(newSize[0]*newSize[1])))); #160000=400*400
frRec = np.concatenate((frRecRemain,frRec), axis=0);
if clIndex > clips[0] or startFrame > clipStart:
frRec = np.concatenate((frRecRemain,frRec), axis=0);
for fb in fbList:
recIm3C = np.zeros((bufferSize,CVNsize,CVNsize,3))
for w in range(0,frRec.shape[0]-windowST):
startWin = w;
endWin = startWin + windowST;
posDic, maxMovement, cfrVectRec, frameVectFloatRec = getting_frame_record(frRec, startWin, endWin,fb, newSize, roi, CVNsize)
im3C = create_3C_image (cfrVectRec,CVNsize)
if modelName != 'none':
predictBehavior = 1 # predict behavior from ST-image and store the label
else:
predictBehavior = 0
if predictBehavior == 1:
X_rs = np.zeros((1,CVNsize,CVNsize,3))
X_rs[0,:,:,:]=im3C
X = X_rs/256 # normalize
predictionsProb = model.predict(X)
predictionLabel = np.zeros((1,np.shape(predictionsProb)[0]))
predictionLabel[0,:] = np.argmax(predictionsProb,axis=1)
#cv2.imshow('im3C',im3C)
recIm3C[w,:,:,:]=im3C
xPos = posDic["xPos"];
yPos = posDic["yPos"];
if w == 0:
global xPosRec #AER
xPosRec = xPos;
global yPosRec #AER
yPosRec = yPos;
global maxMovementRec #AER
maxMovementRec = maxMovement
if modelName != 'none':
global behPredictionRec#AER
behPredictionRec = predictionLabel
else: behPredictionRec = 0
if w > 0:
xPosRec = np.vstack((xPosRec,xPos));
yPosRec = np.vstack((yPosRec,yPos));
maxMovementRec = np.vstack((maxMovementRec,maxMovement));
if modelName != 'none':
behPredictionRec = np.vstack((behPredictionRec,predictionLabel))
else: behPredictionRec = 0
xPosRec=0 #AER
yPosRec=0 #AER
dictPosRec = {"xPosRec" : xPosRec, "yPosRec" : yPosRec};
maxMovementRec=0 #AER
behPredictionRec=0 #AER
dictST = {"recIm3C" : recIm3C, "dictPosRec" : dictPosRec, "maxMovementRec" : maxMovementRec, "behPredictionRec" : behPredictionRec};
nameSMRec = 'dict3C_' + fileName[0:-4] + '_Arena1_' + str('%06.0f' % bf)
if OSplatform == 'Linux':
#newPath = dirPathOutput + '/' + fileName[0:-4] + '_fb' + str(fb) #!!!!!!works with non-numbered clips (one clip per video recording)
newPath = dirPathOutput + '/' + fileName[0:-4] + '_Arena1' #!!!!!!works with numbered clips (multiple clips of the same video; clip names end with index number)
if OSplatform == 'Windows':
#newPath = dirPathOutput + '\\' + fileName[0:-4] + '_fb' + str(fb) #!!!!!!works with non-numbered clips (one clip per video recording)
newPath = dirPathOutput + '\\' + fileName[0:-4] + '_Arena1' #!!!!!!works with numbered clips (multiple clips of the same video; clip names end with index number)
if OSplatform == 'Darwin':
#newPath = dirPathOutput + '/' + fileName[0:-4] + '_fb' + str(fb) #!!!!!!works with non-numbered clips (one clip per video recording)
newPath = dirPathOutput + '/' + fileName[0:-4] + '_Arena1' #!!!!!!works with numbered clips (multiple clips of the same video; clip names end with index number)
if not os.path.exists(newPath):
os.mkdir(newPath);
if OSplatform == 'Linux':
fileDirPathOutputName = newPath + '/' + nameSMRec;
if OSplatform == 'Windows':
fileDirPathOutputName = newPath + '\\' + nameSMRec;
if OSplatform == 'Darwin':
fileDirPathOutputName = newPath + '/' + nameSMRec;
with open(fileDirPathOutputName, "wb") as f:
pickle.dump(dictST, f)
frRecSh = frRec.shape;
frRecRemain = frRec[bufferSize:frRecSh[0],:]
clIndex = clIndex +1;
print(clIndex)
#Batch part:
# videoFolderList = sorted(next(os.walk(rawVidDirPath))[2]); #list only the files, not directories
videoFolderList = sorted(os.listdir(rawVidDirPath)); #list of files and directories
sz = np.shape(videoFolderList); sizeVideoFolder = sz[0];
for fld in range(firstFolder, sizeVideoFolder):
print(fld)
currentVideoFolder = videoFolderList[fld];
if currentVideoFolder[-5:] != 'Store' :
dirPathInput = rawVidDirPath #+ '/' + currentVideoFolder;
# clipList = sorted(next(os.walk(dirPathInput))[2]);
clipList = sorted(os.listdir(dirPathInput));
szClipList = np.shape(clipList);
clipsNumber = szClipList[0];
if clipsNumber > clipsNumberMax:
clipsNumber = clipsNumberMax;
video_clips_to_3C_image_fun (dirPathInput,dirPathOutput,fbList,clipStart,clipEnd,clipsNumber,bufferSize,windowST,modelName,OSplatform,roi,CVNsize);
# #Batch part:
# videoFileList = sorted(next(os.walk(rawVidDirPath))[2]); #list only the files, not directories
# for nf in range(1,len(videoFileList)):
# currentFile = videoFileList[nf];
# dirPathInput = rawVidDirPath
# clipsNumber = len(videoFileList);
# video_clips_to_3C_image_fun (dirPathInput,dirPathOutput,fbList,clipStart,clipEnd,clipsNumber,bufferSize,windowST,modelName,OSplatform,roi,CVNsize);