-
Notifications
You must be signed in to change notification settings - Fork 0
/
multianimal_my_projeto_dlc_doutorado.py
240 lines (176 loc) · 9.83 KB
/
multianimal_my_projeto_dlc_doutorado.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
# -*- coding: utf-8 -*-
"""MultiAnimal_MY PROJETO DLC DOUTORADO
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1rKq2WdLscjERSSPcrX213q-MZLETcHCf
"""
import tensorflow as tf
from google.colab import drive
drive.mount('/content/drive')
# modify this!!
#labeled_data_dir = '/content/drive/My Drive/DLC_Multi/Maria-Social-2023-03-23/videos'
!pip install deeplabcut
#This is for correction in erros with 2.3rc.2
import pandas as pd
import os
all_videos = os.listdir(labeled_data_dir)
for video_name in all_videos:
if os.path.isdir(os.path.join(labeled_data_dir, video_name)):
video_name_dir = os.path.join(labeled_data_dir, video_name)
for file in os.listdir(video_name_dir):
if file.startswith('CollectedData') and file.endswith(".h5"):
file_path = os.path.join(video_name_dir, file)
data = pd.read_hdf(file_path)
if data.index[0][0] == 'labeled-data':
continue
new_data = pd.concat({video_name: data})
new_new_data = pd.concat({'labeled-data': new_data})
new_new_data.to_hdf(file_path, key='df', mode='w')
print('Modified ', file_path)
# Commented out IPython magic to ensure Python compatibility.
!pip install deeplabcut
# %reload_ext numpy
# %reload_ext scipy
# %reload_ext matplotlib
# %reload_ext mpl_toolkits
!pip install --upgrade deeplabcut
import os
# Commented out IPython magic to ensure Python compatibility.
os.environ ['DLClight'] = 'True'
os.environ ['Colab'] = 'True'
# %cd /content/drive/My Drive/DLC_Multi
"""%% TREINAR A REDE"""
import os
import deeplabcut
drive_path = '/content/drive/My Drive/Maria-Social-2023-03-23/config.yaml'
import os
import deeplabcut
drive_path = '/content/drive/My Drive/Maria-Social-2023-03-23/config.yaml'
shuffle = 1 #edit if needed; 1 is the default.
#my_better_graph = [[1, 2], [1, 3], [1, 4],[4, 5], [5, 6]]
deeplabcut.create_multianimaltraining_dataset(drive_path, Shuffles=[1], paf_graph='config')
paf_graph='config' #adicional para deixar skeleto do jeito q eu sugeri, identity=True
deeplabcut.train_network (drive_path, allow_growth=True, max_snapshots_to_keep=8, saveiters=10000, maxiters=100000)
"""%% AVALIAR REDE TREINADA"""
import os
import deeplabcut
drive_path = '/content/drive/My Drive/Maria-Social-2023-03-23/config.yaml'
deeplabcut.evaluate_network(drive_path,Shuffles=[1], plotting='individual')
"""#plotar os mapas de pontuação, camadas locref e PAFs:"""
import os
import deeplabcut
drive_path = '/content/drive/My Drive/Maria-Social-2023-03-23/config.yaml'
deeplabcut.extract_save_all_maps(drive_path, shuffle=1, Indices=[0, 5])
#@title Texto de título padrão
scorername = deeplabcut.analyze_videos(drive_path,['/content/drive/My Drive/DLC_Multi/Maria-Social-2023-03-23/videos/G67B1TDAVtake02.avi'], videotype='.avi')
deeplabcut.create_video_with_all_detections(drive_path, ['/content/drive/My Drive/DLC_Multi/Maria-Social-2023-03-23/videos/G67B1TDAVtake02.avi'], videotype='.avi')
scorername = deeplabcut.analyze_videos(drive_path,['/content/drive/My Drive/DLC_Multi/Maria-Social-2023-03-23/videos/G69B2TDAVtake03.avi'], videotype='.avi')
deeplabcut.create_video_with_all_detections(drive_path, ['/content/drive/My Drive/DLC_Multi/Maria-Social-2023-03-23/videos/G69B2TDAVtake03.avi'], videotype='.avi')
import os
import deeplabcut
drive_path = '/content/drive/My Drive/DLC_Multi/Maria-Social-2023-03-23/config.yaml'
deeplabcut.utils.plot_edge_affinity_distributions('/content/drive/My Drive/DLC_Multi/Maria-Social-2023-03-23/videos/G69B2TDBPtake05DLC_dlcrnetms5_MariaMar23shuffle1_90000_meta.pickle', include_bodyparts='all', output_name='teste', figsize=(10, 7))
"""não lembro o que é"""
deeplabcut.pose_estimation_tensorflow.core.evaluate.avaliar_network ( drive_path , Shuffles = [1] , trainingsetindex = 0 , plotting = True , show_errors = True , comparaçãobodyparts = 'all' , rescale = False )
"""% CONVERTER VÍDEOS (opicional)"""
ffmpeg -i '/content/drive/My Drive/DLC_Multi/Maria-Social-2023-03-23/videos' -c:v h264 -crf 18 -preset fast '/content/drive/My Drive/DLC_Multi/Maria-Social-2023-03-23/videos2'
"""%% ANALYSE VIDEO"""
import os
import deeplabcut
drive_path = '/content/drive/My Drive/Maria-Social-2023-03-23/config.yaml'
deeplabcut.analyze_videos(drive_path,
['/content/drive/My Drive/Maria-Social-2023-03-23/videos/G67B1TDAVtake02.avi',
'/content/drive/My Drive/Maria-Social-2023-03-23/videos/G67B1TDBPtake05.avi',
'/content/drive/My Drive//Maria-Social-2023-03-23/videos/G69B2TDAVtake03.avi',
'/content/drive/My Drive/Maria-Social-2023-03-23/videos/G69B2TDBPtake05.avi',
], videotype='avi', robust_nframes=bool, shuffle=1, save_as_csv = True, auto_track=True)
import os
import deeplabcut
drive_path = '/content/drive/My Drive/Maria-Social-2023-03-23/config.yaml'
deeplabcut.transformer_reID(drive_path, ['/content/drive/My Drive/Maria-Social-2023-03-23/videos/G67B1TDAVtake02.avi'], n_tracks=2, videotype='avi')
"""%Filtro track"""
import os
import deeplabcut
drive_path = '/content/drive/My Drive/Maria-Social-2023-03-23/config.yaml'
deeplabcut.filterpredictions(drive_path,
['/content/drive/My Drive/Maria-Social-2023-03-23/videos/G67B1TDAVtake02.avi',
'/content/drive/My Drive//Maria-Social-2023-03-23/videos/G67B1TDBPtake05.avi',
'/content/drive/My Drive/Maria-Social-2023-03-23/videos/G69B2TDAVtake03.avi',
'/content/drive/My Drive/Maria-Social-2023-03-23/videos/G69B2TDBPtake05.avi',
], videotype='avi',
filtertype= 'arima',ARdegree=3, MAdegree=1)
"""%Plot track"""
import os
import deeplabcut
drive_path = '/content/drive/My Drive/Maria-Social-2023-03-23/config.yaml'
deeplabcut.plot_trajectories(drive_path, [
'/content/drive/My Drive/Maria-Social-2023-03-23/videos/G67B1TDAVtake02.avi',
'/content/drive/My Drive/Maria-Social-2023-03-23/videos/G67B1TDBPtake05.avi',
'/content/drive/My Drive/Maria-Social-2023-03-23/videos/G69B2TDAVtake03.avi',
'/content/drive/My Drive/Maria-Social-2023-03-23/videos/G69B2TDBPtake05.avi'],filtered=True)
"""%% Videos Rotulados"""
import os
import deeplabcut
drive_path = '/content/drive/My Drive/Maria-Social-2023-03-23/config.yaml'
deeplabcut.create_labeled_video(drive_path, [
'/content/drive/My Drive/Maria-Social-2023-03-23/videos/G69B2TDBPtake05.avi',
], trainingsetindex=0, trailpoints=10, draw_skeleton = False, save_frames=False, fastmode=True, filtered=True, color_by='individuals')
deeplabcut.transformer_reID(drive_path, ['/content/drive/My Drive/DLC/multi/videos/G67B1S2DAVtake32.avi'], n_tracks=2, videotype="avi")
save_frames=True OR keypoints_only=True
"""%Refinamento de frames outlier
"""
import os
import deeplabcut
drive_path = '/content/drive/My Drive/DLC_Multi/Maria-Social-2023-03-23/config.yaml'
deeplabcut.find_outliers_in_raw_data(drive_path, '/content/drive/My Drive/DLC_Multi/Maria-Social-2023-03-23/videos/G67B1TDAVtake02DLC_dlcrnetms5_MariaMar23shuffle1_90000_full.pickle', '/content/drive/My Drive/DLC_Multi/Maria-Social-2023-03-23/videos/G67B1TDAVtake02.avi')
deeplabcut.extract_outlier_frames(config_path, ['videofile_path'] outlieralgorithm='jump' ) #outlieralgorithm:'fitting', 'jump', or 'uncertain'`` #outlieralgorithm='manual')
"""REfinando os labes"""
deeplabcut.refine_labels(config_path)
"""Mesclar conjunto de dados"""
deeplabcut.merge_datasets(config_path)
"""DEPOIS VOLTAR PARA AVALIAR A REDE, EM SEGUIDA ANALISAR OS VIDEOS
Adicionais para filtro do track
"""
convert_detections2tracklets(identity_only=False)
deeplabcut.utils.make_labeled_video.create_video_from_pickled_tracks
deeplabcut.stitch_tracklets(config_path, ['videofile_path'], videotype='mp4',
shuffle=1, trainingsetindex=0)
deeplabcut.transformer_reID(config, videos_to_analyze, n_tracks=None, videotype="mp4")
deeplabcut.plot_trajectories(config_path,['/fullpath/project/videos/reachingvideo1.avi'],filtered = True)
deeplabcut.refine_tracklets(drive_path, ['/content/drive/My Drive/DLC_Multi/Maria-Social-2023-03-23/videos/G69B2TDAVtake03DLC_dlcrnetms5_MariaMar23shuffle1_100000_el_filtered'], ['/content/drive/My Drive/DLC_Multi/Maria-Social-2023-03-23/videos/G69B2TDAVtake03.avi'],
max_gap=0, min_swap_len=2, min_tracklet_len=2, trail_len=50) #Refinamendo de identidade
deeplabcut.transformer_reID(drive_path, ['/content/drive/My Drive/DLC_Multi/Maria-Social-2023-03-23/videos/G69B2TDAVtake03.avi'], n_tracks=2, videotype="avi")
"""%CODIGO EXEMPLO PRA AVALIAR DISTÂNCIA ENTE DUAS BODY PARTS."""
import numpy as np
import pandas as pd
min_dist = 75.59
df = pd.read_hdf('/content/drive/My Drive/Teste_DLC/VIDEOS/NOR1T1-R1G1DLC_dlcrnetms5_new_projetOct24shuffle1_105000_el_filtered.h5' )
bpt1 = df.xs('part_1', level='bodyparts', axis=1).to_numpy()
bpt2 = df.xs('part_2', level='bodyparts', axis=1).to_numpy()
bpt3 = df.xs('part_3', level='bodyparts', axis=1).to_numpy()
bpt4 = df.xs('part_4', level='bodyparts', axis=1).to_numpy()
bpt5 = df.xs('fucinho', level='bodyparts', axis=1).to_numpy()
# We calculate the vectors from a point to the other
# and group them per frame and per animal.
try:
diff1 = (bpt1 - bpt5).reshape((len(df), -1, 2))
diff2 = (bpt2 - bpt5).reshape((len(df), -1, 2))
diff3 = (bpt3 - bpt5).reshape((len(df), -1, 2))
diff4 = (bpt4 - bpt5).reshape((len(df), -1, 2))
except ValueError:
diff1 = (bpt1 - bpt5).reshape((len(df), -1, 3))
diff2 = (bpt2 - bpt5).reshape((len(df), -1, 3))
diff3 = (bpt3 - bpt5).reshape((len(df), -1, 3))
diff4 = (bpt4 - bpt5).reshape((len(df), -1, 3))
dist1 = np.linalg.norm(diff1, axis=2)
mask1 = np.any(dist1 <= min_dist, axis=1)
dist2 = np.linalg.norm(diff2, axis=2)
mask2 = np.any(dist2 <= min_dist, axis=1)
dist3 = np.linalg.norm(diff3, axis=2)
mask3 = np.any(dist3 <= min_dist, axis=1)
dist4 = np.linalg.norm(diff4, axis=2)
mask4 = np.any(dist4 <= min_dist, axis=1)
flagged_frames1 = df.iloc[mask1].index
flagged_frames2 = df.iloc[mask2].index
flagged_frames3 = df.iloc[mask4].index
flagged_frames4 = df.iloc[mask4].index