Skip to content

Commit bed4c7f

Browse files
authored
update one2, replace load mp4 method
1 parent dc093ef commit bed4c7f

File tree

1 file changed

+58
-105
lines changed

1 file changed

+58
-105
lines changed

dlc/DLC_labeled_video.py

Lines changed: 58 additions & 105 deletions
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,39 @@
11
import numpy as np
2-
import alf.io
3-
from oneibl.one import ONE
2+
from one.api import ONE
43
from pathlib import Path
54
import cv2
6-
import os
7-
from oneibl.webclient import http_download_file_list
5+
import os,fnmatch
86
import matplotlib
97
import pandas as pd
108
# conda install -c conda-forge pyarrow
9+
import os
10+
11+
def Find(pattern, path):
1112

13+
'''
14+
find a local video like so:
15+
flatiron='/home/mic/Downloads/FlatIron'
16+
vids = Find('*.mp4', flatiron)
17+
'''
18+
result = []
19+
for root, dirs, files in os.walk(path):
20+
for name in files:
21+
if fnmatch.fnmatch(name, pattern):
22+
result.append(os.path.join(root, name))
23+
return result
1224

1325
def find_nearest(array, value):
1426
array = np.asarray(array)
1527
idx = (np.abs(array - value)).argmin()
1628
return idx
1729

1830

19-
def download_raw_video(eid, cameras=None):
20-
"""
21-
Downloads the raw video from FlatIron or cache dir.
22-
This allows you to download just one of the
23-
three videos
24-
:param cameras: the specific camera to load
25-
(i.e. 'left', 'right', or 'body') If None all
26-
three videos are downloaded.
27-
:return: the file path(s) of the raw videos
28-
"""
29-
one = ONE()
30-
if cameras:
31-
cameras = [cameras] if isinstance(cameras, str) else cameras
32-
cam_files = ['_iblrig_{}Camera.raw.mp4'.format(cam) for cam in cameras]
33-
datasets = one._alyxClient.get(
34-
'sessions/' + eid)['data_dataset_session_related']
35-
urls = [ds['data_url'] for ds in datasets if ds['name'] in cam_files]
36-
cache_dir = one.path_from_eid(eid).joinpath('raw_video_data')
37-
if not os.path.exists(str(cache_dir)):
38-
os.mkdir(str(cache_dir))
39-
else: # Check if file already downloaded
40-
# cam_files = [fi[:-4] for fi in cam_files] # Remove ext
41-
filenames = [f for f in os.listdir(str(cache_dir))
42-
if any([cam in f for cam in cam_files])]
43-
if filenames:
44-
return [cache_dir.joinpath(file) for file in filenames]
45-
46-
http_download_file_list(
47-
urls,
48-
username=one._par.HTTP_DATA_SERVER_LOGIN,
49-
password=one._par.HTTP_DATA_SERVER_PWD,
50-
cache_dir=str(cache_dir))
51-
52-
return
53-
54-
else:
55-
return one.load(eid, ['_iblrig_Camera.raw'], download_only=True)
56-
57-
5831
def Viewer(eid, video_type, trial_range, save_video=True, eye_zoom=False):
5932
'''
6033
eid: session id, e.g. '3663d82b-f197-4e8b-b299-7b803a155b84'
6134
video_type: one of 'left', 'right', 'body'
6235
trial_range: first and last trial number of range to be shown, e.g. [5,7]
63-
save_video: video is displayed and saved in local folder
36+
save_video: video is saved this local folder
6437
6538
Example usage to view and save labeled video with wheel angle:
6639
Viewer('3663d82b-f197-4e8b-b299-7b803a155b84', 'left', [5,7])
@@ -72,47 +45,33 @@ def Viewer(eid, video_type, trial_range, save_video=True, eye_zoom=False):
7245
return 'Last character of save_vids_here must be slash'
7346

7447
one = ONE()
75-
dataset_types = ['camera.times',
76-
'wheel.position',
77-
'wheel.timestamps',
78-
'trials.intervals',
79-
'camera.dlc']
80-
81-
a = one.list(eid, 'dataset-types')
82-
83-
assert all([i in a for i in dataset_types]
84-
), 'For this eid, not all data available'
85-
86-
D = one.load(eid, dataset_types=dataset_types, dclass_output=True)
87-
alf_path = Path(D.local_path[0]).parent.parent / 'alf'
48+
alf_path = one.eid2path(eid)
8849

8950
# Download a single video
90-
video_data = alf_path.parent / 'raw_video_data'
91-
download_raw_video(eid, cameras=[video_type])
92-
video_path = list(
93-
video_data.rglob(
94-
'_iblrig_%sCamera.raw.*' %
95-
video_type))[0]
96-
print(video_path)
97-
98-
# that gives cam time stamps and DLC output (change to alf_path eventually)
99-
100-
cam = alf.io.load_object(
101-
alf_path,
102-
'%sCamera' %
103-
video_type,
104-
namespace='ibl')
105-
106-
# just to read in times for newer data (which has DLC results in pqt format
107-
# cam = alf.io.load_object(alf_path, '_ibl_%sCamera' % video_type)
108-
109-
# set where to read and save video and get video info
51+
video_path = (alf_path /
52+
f'raw_video_data/_iblrig_{video_type}Camera.raw.mp4')
53+
54+
if not os.path.isfile(video_path):
55+
print('mp4 not found locally, downloading it ...')
56+
video_path = one.load_dataset(eid,
57+
f'raw_video_data/_iblrig_{video_type}Camera.raw.mp4',
58+
download_only=True)
59+
60+
# Get trials info
61+
trials = one.load_object(eid, 'trials', download_only=True)
62+
63+
64+
# Download DLC traces and stamps
65+
Times = one.load_dataset(eid,f'alf/_ibl_{video_type}Camera.times.npy')
66+
cam = one.load_dataset(eid,f'alf/_ibl_{video_type}Camera.dlc.pqt')
67+
68+
# get video info
11069
cap = cv2.VideoCapture(video_path.as_uri())
11170
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
11271
fps = cap.get(cv2.CAP_PROP_FPS)
11372
size = (int(cap.get(3)), int(cap.get(4)))
11473

115-
assert length < len(cam['times']), '#frames > #stamps'
74+
11675
print(eid,
11776
', ',
11877
video_type,
@@ -121,26 +80,26 @@ def Viewer(eid, video_type, trial_range, save_video=True, eye_zoom=False):
12180
', #frames:',
12281
length,
12382
', #stamps:',
124-
len(cam['times']),
83+
len(Times),
12584
', #frames - #stamps = ',
126-
length - len(cam['times']))
85+
length - len(Times))
12786

12887
# pick trial range for which to display stuff
129-
trials = alf.io.load_object(alf_path, 'trials', namespace='ibl')
88+
trials = one.load_object(eid, 'trials')
13089
num_trials = len(trials['intervals'])
13190
if trial_range[-1] > num_trials - 1:
13291
print('There are only %s trials' % num_trials)
133-
134-
frame_start = find_nearest(cam['times'],
92+
print('There are %s trials' % num_trials)
93+
frame_start = find_nearest(Times,
13594
[trials['intervals'][trial_range[0]][0]])
136-
frame_stop = find_nearest(cam['times'],
95+
frame_stop = find_nearest(Times,
13796
[trials['intervals'][trial_range[-1]][1]])
13897

13998
'''
140-
wheel related stuff
99+
load wheel
141100
'''
142101

143-
wheel = alf.io.load_object(alf_path, 'wheel', namespace='ibl')
102+
wheel = one.load_object(eid, 'wheel')
144103
import brainbox.behavior.wheel as wh
145104
try:
146105
pos, t = wh.interpolate_position(
@@ -159,7 +118,7 @@ def Viewer(eid, video_type, trial_range, save_video=True, eye_zoom=False):
159118
# alignment of cam stamps and interpolated wheel stamps
160119
wheel_pos = []
161120
kk = 0
162-
for wt in cam['times'][frame_start:frame_stop]:
121+
for wt in Times[frame_start:frame_stop]:
163122
wheel_pos.append(pos_int[find_nearest(t_int, wt)])
164123
kk += 1
165124
if kk % 3000 == 0:
@@ -168,26 +127,14 @@ def Viewer(eid, video_type, trial_range, save_video=True, eye_zoom=False):
168127
'''
169128
DLC related stuff
170129
'''
171-
Times = cam['times'][frame_start:frame_stop]
172-
del cam['times']
130+
Times = Times[frame_start:frame_stop]
173131

174132
# some exception for inconsisitent data formats
175-
try:
176-
dlc_name = '_ibl_%sCamera.dlc.pqt' % video_type
177-
dlc_path = alf_path / dlc_name
178-
cam = pd.read_parquet(dlc_path, engine="fastparquet")
179-
print('it is pqt')
180-
except BaseException:
181-
raw_vid_path = alf_path.parent / 'raw_video_data'
182-
cam = alf.io.load_object(
183-
raw_vid_path,
184-
'%sCamera' %
185-
video_type,
186-
namespace='ibl')
187133

134+
135+
188136
points = np.unique(['_'.join(x.split('_')[:-1]) for x in cam.keys()])
189137
if len(points) == 1:
190-
cam = cam['dlc']
191138
points = np.unique(['_'.join(x.split('_')[:-1]) for x in cam.keys()])
192139

193140
if video_type != 'body':
@@ -319,19 +266,25 @@ def Viewer(eid, video_type, trial_range, save_video=True, eye_zoom=False):
319266
# col = np.array([0, 0, 255]) # all points red
320267
X = X.astype(int)
321268
Y = Y.astype(int)
269+
# cv2.imshow('frame', gray)
270+
# print(gray.shape)
271+
# print(X - dot_s,X + dot_s, Y - dot_s,Y + dot_s)
322272
gray[X - dot_s:X + dot_s, Y - dot_s:Y + dot_s] = block * col
323273
ll += 1
324274

325275
gray = gray[y0:y1, x0:x1]
326276
if save_video:
327277
out.write(gray)
328-
cv2.imshow('frame', gray)
329-
cv2.waitKey(1)
278+
#cv2.imshow('frame', gray)
279+
#cv2.waitKey(1)
330280
k += 1
331281
if k == (frame_stop - frame_start) - 1:
332282
break
333283

334284
if save_video:
335285
out.release()
336286
cap.release()
337-
cv2.destroyAllWindows()
287+
#cv2.destroyAllWindows()
288+
289+
print(eid, video_type, frame_stop, frame_start)
290+
#return XYs, Times

0 commit comments

Comments
 (0)