-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvideoExample.py
137 lines (112 loc) · 5.47 KB
/
videoExample.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
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 14 10:40:50 2023
@author: svc_ccg
"""
import glob
import os
import h5py
import numpy as np
import cv2
import skvideo
skvideo.setFFmpegPath('C:\\Users\\svc_ccg\\Desktop\\ffmpeg\\bin')
import skvideo.io
from maskTaskAnalysisUtils import MaskTaskData
outputDir = r"\\allen\programs\braintv\workgroups\tiny-blue-dot\masking\Sam\Presentations\video_example"
behavFilesDir = r"\\allen\programs\braintv\workgroups\tiny-blue-dot\masking\Sam\Analysis\Data\masking\wt"
dataDir = r"\\allen\programs\braintv\workgroups\tiny-blue-dot\masking\Data"
showMouse = False
if showMouse:
stimNames = ('target_left','target_right','mask','gray')
else :
stimNames = ('target_left_small_high_res','target_right_small_high_res','mask_small_high_res','gray_high_res')
leftTarget,rightTarget,mask,gray = [cv2.imread(os.path.join(outputDir,stim+'.png'),cv2.IMREAD_GRAYSCALE) for stim in stimNames]
if not showMouse:
imgs = (leftTarget,rightTarget,mask,gray)
newH,newW = [min(img.shape[i] for img in imgs) for i in (0,1)]
newImgs = []
for img in imgs:
h,w = img.shape
x = (w-newW)//2
y = (h-newH)//2
newImgs.append(img[y:y+newH,x:x+newW])
leftTarget,rightTarget,mask,gray = newImgs
behavFiles = glob.glob(os.path.join(behavFilesDir,'*.hdf5'))
for f in behavFiles:
obj = MaskTaskData()
obj.loadBehavData(f)
mouseId = f[-27:-21]
expDate = f[-16:-12] + f[-20:-16]
if showMouse:
syncPath = glob.glob(os.path.join(dataDir,mouseId+'_'+expDate,'Sync*.hdf5'))
if len(syncPath) == 0:
continue
syncPath = syncPath[0]
videoPath = glob.glob(os.path.join(dataDir,mouseId+'_'+expDate,'BehavCam*.mp4'))[0]
syncFile = h5py.File(syncPath,'r')
syncData = syncFile['AnalogInput']
syncSampleRate = syncData.attrs.get('sampleRate')
syncChannelNames = syncData.attrs.get('channelNames')
syncSampInt = 1/syncSampleRate
syncTime = np.arange(syncSampInt,syncSampInt*syncData.shape[0]+syncSampInt,syncSampInt)
vsync = syncData[:,np.where(syncChannelNames=='vsync')[0][0]]
fallingEdges = np.concatenate(([False],(vsync[1:]-vsync[:-1]) < -0.5))
vsyncTimes = syncTime[fallingEdges]
vsyncIntervals = np.diff(vsyncTimes)
vsyncTimes = vsyncTimes[np.concatenate(([True],vsyncIntervals>0.1*vsyncIntervals.mean()))]
if vsyncTimes.size != obj.behavFrameIntervals.size+1:
continue
camSync = syncData[:,np.where(syncChannelNames=='cam1Exposure')[0][0]]
risingEdges = np.concatenate(([False],(camSync[1:]-camSync[:-1]) > 0.5))
camSyncTimes = syncTime[risingEdges]
camSyncIntervals = np.diff(camSyncTimes)
camSyncTimes = camSyncTimes[np.concatenate(([True],camSyncIntervals>0.1*camSyncIntervals.mean()))]
camFrameData = h5py.File(os.path.join(videoPath[:-3]+'hdf5'),'r')
camFrameTimes = camFrameData['frameTimes'][()]
camFrameTimes -= camFrameTimes[0]
camFrameIntervals = np.diff(camFrameTimes)
camFrameIndex = np.searchsorted(camSyncTimes,vsyncTimes)
videoIn = cv2.VideoCapture(videoPath)
isFrame,videoFrame = videoIn.read()
videoFrame = cv2.cvtColor(videoFrame,cv2.COLOR_BGR2GRAY)
exampleTrials = []
for i in range(obj.ntrials-3):
if np.all((obj.trialType[i:i+3] == ('targetOnly','mask','mask')) &
(obj.maskOnset[i:i+3] == (0,6,2)) &
(obj.response[i:i+3] == (1,1,1))):
exampleTrials.append(i)
inputParams = {'-r': '60'}
outputParams = {'-r': '60', '-vcodec': 'libx264', '-crf': '23', '-preset': 'slow'}
preFrames = 60
postFrames = 120
if showMouse:
crop = np.s_[50:,50:320]
offsetX = int(0.5*(videoFrame[crop].shape[1] - mask.shape[1]))
offsetY = mask.shape[0]
w = videoFrame[crop].shape[1]
h = videoFrame[crop].shape[0]+mask.shape[0]
else:
offsetX = offsetY = 0
h,w = mask.shape
for trialIndex in exampleTrials:
videoData = np.zeros((3*(preFrames+postFrames),h,w),dtype=np.uint8)
videoData[:,:mask.shape[0],offsetX:offsetX+mask.shape[1]] = gray[None,:,:]
for i in range(3):
j = i*(preFrames+postFrames)+preFrames
videoData[j,:mask.shape[0],offsetX:offsetX+mask.shape[1]] = leftTarget if obj.rewardDir[trialIndex+i]==1 else rightTarget
maskOnset = int(obj.maskOnset[trialIndex+i]/2)
if maskOnset > 0:
videoData[j+maskOnset:j+39,:mask.shape[0],offsetX:offsetX+mask.shape[1]] = mask[None,:,:]
if showMouse:
startFrame = obj.trialStartFrame[trialIndex+i]
for j,behavFrame in enumerate(range(startFrame-preFrames*2,startFrame+postFrames*2,2)):
videoIn.set(cv2.CAP_PROP_POS_FRAMES,camFrameIndex[behavFrame])
isFrame,videoFrame = videoIn.read()
videoFrame = cv2.cvtColor(videoFrame,cv2.COLOR_BGR2GRAY)
videoData[i*(preFrames+postFrames)+j,offsetY:,:] = videoFrame[crop]
savePath = os.path.join(outputDir,'masking_example_'+mouseId+'_'+expDate+'_trial'+str(trialIndex))
savePath += '.mp4' if showMouse else '_no_mouse.mp4'
v = skvideo.io.FFmpegWriter(savePath,inputdict=inputParams,outputdict=outputParams)
for d in videoData:
v.writeFrame(d)
v.close()