-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathpredict_videos.py
1860 lines (1623 loc) · 70.6 KB
/
predict_videos.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
#
# DeepLabCut Toolbox (deeplabcut.org)
# © A. & M.W. Mathis Labs
# https://github.com/DeepLabCut/DeepLabCut
#
# Please see AUTHORS for contributors.
# https://github.com/DeepLabCut/DeepLabCut/blob/master/AUTHORS
#
# Licensed under GNU Lesser General Public License v3.0
#
####################################################
# Dependencies
####################################################
import argparse
import os
import os.path
import pickle
import re
import time
import warnings
from pathlib import Path
import cv2
import numpy as np
import pandas as pd
import tensorflow as tf
from scipy.optimize import linear_sum_assignment
from skimage.util import img_as_ubyte
from tqdm import tqdm
from deeplabcut.core import trackingutils, inferenceutils
from deeplabcut.pose_estimation_tensorflow.config import load_config
from deeplabcut.pose_estimation_tensorflow.core import predict
from deeplabcut.refine_training_dataset.stitch import stitch_tracklets
from deeplabcut.utils import auxiliaryfunctions, auxfun_multianimal, auxfun_models
from deeplabcut.pose_estimation_tensorflow.core.openvino.session import (
GetPoseF_OV,
is_openvino_available,
)
####################################################
# Loading data, and defining model folder
####################################################
def create_tracking_dataset(
config,
videos,
track_method,
videotype="",
shuffle=1,
trainingsetindex=0,
gputouse=None,
save_as_csv=False,
destfolder=None,
batchsize=None,
cropping=None,
TFGPUinference=True,
dynamic=(False, 0.5, 10),
modelprefix="",
robust_nframes=False,
n_triplets=1000,
):
try:
from deeplabcut.pose_tracking_pytorch import create_triplets_dataset
except ModuleNotFoundError:
raise ModuleNotFoundError(
"Unsupervised identity learning requires PyTorch. Please run `pip install torch`."
)
from deeplabcut.pose_estimation_tensorflow.predict_multianimal import (
extract_bpt_feature_from_video,
)
# allow_growth must be true here because tensorflow does not automatically free gpu memory and setting it as false occupies all gpu memory so that pytorch cannot kick in
allow_growth = True
if "TF_CUDNN_USE_AUTOTUNE" in os.environ:
del os.environ["TF_CUDNN_USE_AUTOTUNE"] # was potentially set during training
if gputouse is not None: # gpu selection
auxfun_models.set_visible_devices(gputouse)
tf.compat.v1.reset_default_graph()
start_path = os.getcwd() # record cwd to return to this directory in the end
cfg = auxiliaryfunctions.read_config(config)
trainFraction = cfg["TrainingFraction"][trainingsetindex]
if cropping is not None:
cfg["cropping"] = True
cfg["x1"], cfg["x2"], cfg["y1"], cfg["y2"] = cropping
print("Overwriting cropping parameters:", cropping)
print("These are used for all videos, but won't be save to the cfg file.")
modelfolder = os.path.join(
cfg["project_path"],
str(
auxiliaryfunctions.get_model_folder(
trainFraction, shuffle, cfg, modelprefix=modelprefix
)
),
)
path_test_config = Path(modelfolder) / "test" / "pose_cfg.yaml"
try:
dlc_cfg = load_config(str(path_test_config))
except FileNotFoundError:
raise FileNotFoundError(
"It seems the model for shuffle %s and trainFraction %s does not exist."
% (shuffle, trainFraction)
)
Snapshots = auxiliaryfunctions.get_snapshots_from_folder(
train_folder=Path(modelfolder) / "train",
)
if cfg["snapshotindex"] == "all":
print(
"Snapshotindex is set to 'all' in the config.yaml file. Running video analysis with all snapshots is very costly! Use the function 'evaluate_network' to choose the best the snapshot. For now, changing snapshot index to -1!"
)
snapshotindex = -1
else:
snapshotindex = cfg["snapshotindex"]
print("Using %s" % Snapshots[snapshotindex], "for model", modelfolder)
##################################################
# Load and setup CNN part detector
##################################################
# Check if data already was generated:
dlc_cfg["init_weights"] = os.path.join(
modelfolder, "train", Snapshots[snapshotindex]
)
trainingsiterations = (dlc_cfg["init_weights"].split(os.sep)[-1]).split("-")[-1]
# Update number of output and batchsize
dlc_cfg["num_outputs"] = cfg.get("num_outputs", dlc_cfg.get("num_outputs", 1))
if batchsize is None:
# update batchsize (based on parameters in config.yaml)
dlc_cfg["batch_size"] = cfg["batch_size"]
else:
dlc_cfg["batch_size"] = batchsize
cfg["batch_size"] = batchsize
if "multi-animal" in dlc_cfg["dataset_type"]:
dynamic = (False, 0.5, 10) # setting dynamic mode to false
TFGPUinference = False
if dynamic[0]: # state=true
# (state,detectiontreshold,margin)=dynamic
print("Starting analysis in dynamic cropping mode with parameters:", dynamic)
dlc_cfg["num_outputs"] = 1
TFGPUinference = False
dlc_cfg["batch_size"] = 1
print(
"Switching batchsize to 1, num_outputs (per animal) to 1 and TFGPUinference to False (all these features are not supported in this mode)."
)
# Name for scorer:
DLCscorer, DLCscorerlegacy = auxiliaryfunctions.get_scorer_name(
cfg,
shuffle,
trainFraction,
trainingsiterations=trainingsiterations,
modelprefix=modelprefix,
)
if dlc_cfg["num_outputs"] > 1:
if TFGPUinference:
print(
"Switching to numpy-based keypoint extraction code, as multiple point extraction is not supported by TF code currently."
)
TFGPUinference = False
print("Extracting ", dlc_cfg["num_outputs"], "instances per bodypart")
xyz_labs_orig = ["x", "y", "likelihood"]
suffix = [str(s + 1) for s in range(dlc_cfg["num_outputs"])]
suffix[0] = "" # first one has empty suffix for backwards compatibility
xyz_labs = [x + s for s in suffix for x in xyz_labs_orig]
else:
xyz_labs = ["x", "y", "likelihood"]
if TFGPUinference:
sess, inputs, outputs = predict.setup_GPUpose_prediction(
dlc_cfg, allow_growth=allow_growth
)
else:
sess, inputs, outputs, extra_dict = predict.setup_pose_prediction(
dlc_cfg, allow_growth=allow_growth, collect_extra=True
)
pdindex = pd.MultiIndex.from_product(
[[DLCscorer], dlc_cfg["all_joints_names"], xyz_labs],
names=["scorer", "bodyparts", "coords"],
)
##################################################
# Looping over videos
##################################################
Videos = auxiliaryfunctions.get_list_of_videos(videos, videotype)
if len(Videos) > 0:
if "multi-animal" in dlc_cfg["dataset_type"]:
for video in Videos:
extract_bpt_feature_from_video(
video,
DLCscorer,
trainFraction,
cfg,
dlc_cfg,
sess,
inputs,
outputs,
extra_dict,
destfolder=destfolder,
robust_nframes=robust_nframes,
)
# should close tensorflow session here in order to free gpu
sess.close()
tf.keras.backend.clear_session()
create_triplets_dataset(
Videos,
DLCscorer,
track_method,
n_triplets=n_triplets,
destfolder=destfolder,
)
else:
raise NotImplementedError("not implemented")
os.chdir(str(start_path))
if "multi-animal" in dlc_cfg["dataset_type"]:
print(
"If the tracking is not satisfactory for some videos, consider expanding the training set. You can use the function 'extract_outlier_frames' to extract a few representative outlier frames."
)
else:
print(
"The videos are analyzed. Now your research can truly start! \n You can create labeled videos with 'create_labeled_video'"
)
print(
"If the tracking is not satisfactory for some videos, consider expanding the training set. You can use the function 'extract_outlier_frames' to extract a few representative outlier frames."
)
return DLCscorer # note: this is either DLCscorer or DLCscorerlegacy depending on what was used!
else:
print("No video(s) were found. Please check your paths and/or 'videotype'.")
return DLCscorer
def analyze_videos(
config,
videos,
videotype="",
shuffle=1,
trainingsetindex=0,
gputouse=None,
save_as_csv=False,
in_random_order=True,
destfolder=None,
batchsize=None,
cropping=None,
TFGPUinference=True,
dynamic=(False, 0.5, 10),
modelprefix="",
robust_nframes=False,
allow_growth=False,
use_shelve=False,
auto_track=True,
n_tracks=None,
animal_names=None,
calibrate=False,
identity_only=False,
use_openvino="CPU" if is_openvino_available else None,
):
"""Makes prediction based on a trained network.
The index of the trained network is specified by parameters in the config file
(in particular the variable 'snapshotindex').
The labels are stored as MultiIndex Pandas Array, which contains the name of
the network, body part name, (x, y) label position in pixels, and the
likelihood for each frame per body part. These arrays are stored in an
efficient Hierarchical Data Format (HDF) in the same directory where the video
is stored. However, if the flag save_as_csv is set to True, the data can also
be exported in comma-separated values format (.csv), which in turn can be
imported in many programs, such as MATLAB, R, Prism, etc.
Parameters
----------
config: str
Full path of the config.yaml file.
videos: list[str]
A list of strings containing the full paths to videos for analysis or a path to
the directory, where all the videos with same extension are stored.
videotype: str, optional, default=""
Checks for the extension of the video in case the input to the video is a
directory. Only videos with this extension are analyzed. If left unspecified,
videos with common extensions ('avi', 'mp4', 'mov', 'mpeg', 'mkv') are kept.
shuffle: int, optional, default=1
An integer specifying the shuffle index of the training dataset used for
training the network.
trainingsetindex: int, optional, default=0
Integer specifying which TrainingsetFraction to use.
By default the first (note that TrainingFraction is a list in config.yaml).
gputouse: int or None, optional, default=None
Indicates the GPU to use (see number in ``nvidia-smi``). If you do not have a
GPU put ``None``.
See: https://nvidia.custhelp.com/app/answers/detail/a_id/3751/~/useful-nvidia-smi-queries
save_as_csv: bool, optional, default=False
Saves the predictions in a .csv file.
in_random_order: bool, optional (default=True)
Whether or not to analyze videos in a random order.
This is only relevant when specifying a video directory in `videos`.
destfolder: string or None, optional, default=None
Specifies the destination folder for analysis data. If ``None``, the path of
the video is used. Note that for subsequent analysis this folder also needs to
be passed.
batchsize: int or None, optional, default=None
Change batch size for inference; if given overwrites value in ``pose_cfg.yaml``.
cropping: list or None, optional, default=None
List of cropping coordinates as [x1, x2, y1, y2].
Note that the same cropping parameters will then be used for all videos.
If different video crops are desired, run ``analyze_videos`` on individual
videos with the corresponding cropping coordinates.
TFGPUinference: bool, optional, default=True
Perform inference on GPU with TensorFlow code. Introduced in "Pretraining
boosts out-of-domain robustness for pose estimation" by Alexander Mathis,
Mert Yüksekgönül, Byron Rogers, Matthias Bethge, Mackenzie W. Mathis.
Source: https://arxiv.org/abs/1909.11229
dynamic: tuple(bool, float, int) triple containing (state, detectiontreshold, margin)
If the state is true, then dynamic cropping will be performed. That means that if an object is detected (i.e. any body part > detectiontreshold),
then object boundaries are computed according to the smallest/largest x position and smallest/largest y position of all body parts. This window is
expanded by the margin and from then on only the posture within this crop is analyzed (until the object is lost, i.e. <detectiontreshold). The
current position is utilized for updating the crop window for the next frame (this is why the margin is important and should be set large
enough given the movement of the animal).
modelprefix: str, optional, default=""
Directory containing the deeplabcut models to use when evaluating the network.
By default, the models are assumed to exist in the project folder.
robust_nframes: bool, optional, default=False
Evaluate a video's number of frames in a robust manner.
This option is slower (as the whole video is read frame-by-frame),
but does not rely on metadata, hence its robustness against file corruption.
allow_growth: bool, optional, default=False.
For some smaller GPUs the memory issues happen. If ``True``, the memory
allocator does not pre-allocate the entire specified GPU memory region, instead
starting small and growing as needed.
See issue: https://forum.image.sc/t/how-to-stop-running-out-of-vram/30551/2
use_shelve: bool, optional, default=False
By default, data are dumped in a pickle file at the end of the video analysis.
Otherwise, data are written to disk on the fly using a "shelf"; i.e., a
pickle-based, persistent, database-like object by default, resulting in
constant memory footprint.
The following parameters are only relevant for multi-animal projects:
auto_track: bool, optional, default=True
By default, tracking and stitching are automatically performed, producing the
final h5 data file. This is equivalent to the behavior for single-animal
projects.
If ``False``, one must run ``convert_detections2tracklets`` and
``stitch_tracklets`` afterwards, in order to obtain the h5 file.
This function has 3 related sub-calls:
identity_only: bool, optional, default=False
If ``True`` and animal identity was learned by the model, assembly and tracking
rely exclusively on identity prediction.
calibrate: bool, optional, default=False
If ``True``, use training data to calibrate the animal assembly procedure. This
improves its robustness to wrong body part links, but requires very little
missing data.
n_tracks: int or None, optional, default=None
Number of tracks to reconstruct. By default, taken as the number of individuals
defined in the config.yaml. Another number can be passed if the number of
animals in the video is different from the number of animals the model was
trained on.
animal_names: list[str], optional
If you want the names given to individuals in the labeled data file, you can
specify those names as a list here. If given and `n_tracks` is None, `n_tracks`
will be set to `len(animal_names)`. If `n_tracks` is not None, then it must be
equal to `len(animal_names)`. If it is not given, then `animal_names` will
be loaded from the `individuals` in the project config.yaml file.
use_openvino: str, optional
Use "CPU" for inference if OpenVINO is available in the Python environment.
Returns
-------
DLCScorer: str
the scorer used to analyze the videos
Examples
--------
Analyzing a single video on Windows
>>> deeplabcut.analyze_videos(
'C:\\myproject\\reaching-task\\config.yaml',
['C:\\yourusername\\rig-95\\Videos\\reachingvideo1.avi'],
)
Analyzing a single video on Linux/MacOS
>>> deeplabcut.analyze_videos(
'/analysis/project/reaching-task/config.yaml',
['/analysis/project/videos/reachingvideo1.avi'],
)
Analyze all videos of type ``avi`` in a folder
>>> deeplabcut.analyze_videos(
'/analysis/project/reaching-task/config.yaml',
['/analysis/project/videos'],
videotype='.avi',
)
Analyze multiple videos
>>> deeplabcut.analyze_videos(
'/analysis/project/reaching-task/config.yaml',
[
'/analysis/project/videos/reachingvideo1.avi',
'/analysis/project/videos/reachingvideo2.avi',
],
)
Analyze multiple videos with ``shuffle=2``
>>> deeplabcut.analyze_videos(
'/analysis/project/reaching-task/config.yaml',
[
'/analysis/project/videos/reachingvideo1.avi',
'/analysis/project/videos/reachingvideo2.avi',
],
shuffle=2,
)
Analyze multiple videos with ``shuffle=2``, save results as an additional csv file
>>> deeplabcut.analyze_videos(
'/analysis/project/reaching-task/config.yaml',
[
'/analysis/project/videos/reachingvideo1.avi',
'/analysis/project/videos/reachingvideo2.avi',
],
shuffle=2,
save_as_csv=True,
)
"""
if "TF_CUDNN_USE_AUTOTUNE" in os.environ:
del os.environ["TF_CUDNN_USE_AUTOTUNE"] # was potentially set during training
if gputouse is not None: # gpu selection
auxfun_models.set_visible_devices(gputouse)
tf.compat.v1.reset_default_graph()
start_path = os.getcwd() # record cwd to return to this directory in the end
cfg = auxiliaryfunctions.read_config(config)
trainFraction = cfg["TrainingFraction"][trainingsetindex]
iteration = cfg["iteration"]
if cropping is not None:
cfg["cropping"] = True
cfg["x1"], cfg["x2"], cfg["y1"], cfg["y2"] = cropping
print("Overwriting cropping parameters:", cropping)
print("These are used for all videos, but won't be save to the cfg file.")
modelfolder = os.path.join(
cfg["project_path"],
str(
auxiliaryfunctions.get_model_folder(
trainFraction, shuffle, cfg, modelprefix=modelprefix
)
),
)
path_test_config = Path(modelfolder) / "test" / "pose_cfg.yaml"
try:
dlc_cfg = load_config(str(path_test_config))
except FileNotFoundError:
raise FileNotFoundError(
"It seems the model for iteration %s and shuffle %s and trainFraction %s does not exist."
% (iteration, shuffle, trainFraction)
)
Snapshots = auxiliaryfunctions.get_snapshots_from_folder(
train_folder=Path(modelfolder) / "train",
)
if cfg["snapshotindex"] == "all":
print(
"Snapshotindex is set to 'all' in the config.yaml file. Running video analysis with all snapshots is very costly! Use the function 'evaluate_network' to choose the best the snapshot. For now, changing snapshot index to -1!"
)
snapshotindex = -1
else:
snapshotindex = cfg["snapshotindex"]
print("Using %s" % Snapshots[snapshotindex], "for model", modelfolder)
##################################################
# Load and setup CNN part detector
##################################################
# Check if data already was generated:
dlc_cfg["init_weights"] = os.path.join(
modelfolder, "train", Snapshots[snapshotindex]
)
trainingsiterations = (dlc_cfg["init_weights"].split(os.sep)[-1]).split("-")[-1]
# Update number of output and batchsize
dlc_cfg["num_outputs"] = cfg.get("num_outputs", dlc_cfg.get("num_outputs", 1))
if batchsize is None:
# update batchsize (based on parameters in config.yaml)
dlc_cfg["batch_size"] = cfg["batch_size"]
else:
dlc_cfg["batch_size"] = batchsize
cfg["batch_size"] = batchsize
if "multi-animal" in dlc_cfg["dataset_type"]:
dynamic = (False, 0.5, 10) # setting dynamic mode to false
TFGPUinference = False
if dynamic[0]: # state=true
# (state,detectiontreshold,margin)=dynamic
print("Starting analysis in dynamic cropping mode with parameters:", dynamic)
dlc_cfg["num_outputs"] = 1
TFGPUinference = False
dlc_cfg["batch_size"] = 1
print(
"Switching batchsize to 1, num_outputs (per animal) to 1 and TFGPUinference to False (all these features are not supported in this mode)."
)
# Name for scorer:
DLCscorer, DLCscorerlegacy = auxiliaryfunctions.get_scorer_name(
cfg,
shuffle,
trainFraction,
trainingsiterations=trainingsiterations,
modelprefix=modelprefix,
)
if dlc_cfg["num_outputs"] > 1:
if TFGPUinference:
print(
"Switching to numpy-based keypoint extraction code, as multiple point extraction is not supported by TF code currently."
)
TFGPUinference = False
print("Extracting ", dlc_cfg["num_outputs"], "instances per bodypart")
xyz_labs_orig = ["x", "y", "likelihood"]
suffix = [str(s + 1) for s in range(dlc_cfg["num_outputs"])]
suffix[0] = "" # first one has empty suffix for backwards compatibility
xyz_labs = [x + s for s in suffix for x in xyz_labs_orig]
else:
xyz_labs = ["x", "y", "likelihood"]
if use_openvino:
sess, inputs, outputs = predict.setup_openvino_pose_prediction(
dlc_cfg, device=use_openvino
)
elif TFGPUinference:
sess, inputs, outputs = predict.setup_GPUpose_prediction(
dlc_cfg, allow_growth=allow_growth
)
else:
sess, inputs, outputs = predict.setup_pose_prediction(
dlc_cfg, allow_growth=allow_growth
)
pdindex = pd.MultiIndex.from_product(
[[DLCscorer], dlc_cfg["all_joints_names"], xyz_labs],
names=["scorer", "bodyparts", "coords"],
)
##################################################
# Looping over videos
##################################################
Videos = auxiliaryfunctions.get_list_of_videos(videos, videotype, in_random_order)
if len(Videos) > 0:
if "multi-animal" in dlc_cfg["dataset_type"]:
from deeplabcut.pose_estimation_tensorflow.predict_multianimal import (
AnalyzeMultiAnimalVideo,
)
for video in Videos:
AnalyzeMultiAnimalVideo(
video,
DLCscorer,
trainFraction,
cfg,
dlc_cfg,
sess,
inputs,
outputs,
destfolder,
robust_nframes=robust_nframes,
use_shelve=use_shelve,
)
if auto_track: # tracker type is taken from default in cfg
convert_detections2tracklets(
config,
[video],
videotype,
shuffle,
trainingsetindex,
destfolder=destfolder,
modelprefix=modelprefix,
calibrate=calibrate,
identity_only=identity_only,
)
stitch_tracklets(
config,
[video],
videotype,
shuffle,
trainingsetindex,
destfolder=destfolder,
n_tracks=n_tracks,
animal_names=animal_names,
modelprefix=modelprefix,
save_as_csv=save_as_csv,
)
else:
for video in Videos:
DLCscorer = AnalyzeVideo(
video,
DLCscorer,
DLCscorerlegacy,
trainFraction,
cfg,
dlc_cfg,
sess,
inputs,
outputs,
pdindex,
save_as_csv,
destfolder,
TFGPUinference,
dynamic,
use_openvino,
)
os.chdir(str(start_path))
if "multi-animal" in dlc_cfg["dataset_type"]:
print(
"The videos are analyzed. Time to assemble animals and track 'em... \n Call 'create_video_with_all_detections' to check multi-animal detection quality before tracking."
)
print(
"If the tracking is not satisfactory for some videos, consider expanding the training set. You can use the function 'extract_outlier_frames' to extract a few representative outlier frames."
)
else:
print(
"The videos are analyzed. Now your research can truly start! \n You can create labeled videos with 'create_labeled_video'"
)
print(
"If the tracking is not satisfactory for some videos, consider expanding the training set. You can use the function 'extract_outlier_frames' to extract a few representative outlier frames."
)
return DLCscorer # note: this is either DLCscorer or DLCscorerlegacy depending on what was used!
else:
print("No video(s) were found. Please check your paths and/or 'video_type'.")
return DLCscorer
def checkcropping(cfg, cap):
print(
"Cropping based on the x1 = %s x2 = %s y1 = %s y2 = %s. You can adjust the cropping coordinates in the config.yaml file."
% (cfg["x1"], cfg["x2"], cfg["y1"], cfg["y2"])
)
nx = cfg["x2"] - cfg["x1"]
ny = cfg["y2"] - cfg["y1"]
if nx > 0 and ny > 0:
pass
else:
raise Exception("Please check the order of cropping parameter!")
if (
cfg["x1"] >= 0
and cfg["x2"] < int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) + 1)
and cfg["y1"] >= 0
and cfg["y2"] < int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) + 1)
):
pass # good cropping box
else:
raise Exception("Please check the boundary of cropping!")
return int(ny), int(nx)
def GetPoseF(cfg, dlc_cfg, sess, inputs, outputs, cap, nframes, batchsize):
"""Batchwise prediction of pose"""
PredictedData = np.zeros(
(nframes, dlc_cfg["num_outputs"] * 3 * len(dlc_cfg["all_joints_names"]))
)
batch_ind = 0 # keeps track of which image within a batch should be written to
batch_num = 0 # keeps track of which batch you are at
ny, nx = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)), int(
cap.get(cv2.CAP_PROP_FRAME_WIDTH)
)
if cfg["cropping"]:
ny, nx = checkcropping(cfg, cap)
frames = np.empty(
(batchsize, ny, nx, 3), dtype="ubyte"
) # this keeps all frames in a batch
pbar = tqdm(total=nframes)
counter = 0
step = max(10, int(nframes / 100))
inds = []
while cap.isOpened():
if counter != 0 and counter % step == 0:
pbar.update(step)
ret, frame = cap.read()
if ret:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
if cfg["cropping"]:
frames[batch_ind] = img_as_ubyte(
frame[cfg["y1"] : cfg["y2"], cfg["x1"] : cfg["x2"]]
)
else:
frames[batch_ind] = img_as_ubyte(frame)
inds.append(counter)
if batch_ind == batchsize - 1:
pose = predict.getposeNP(frames, dlc_cfg, sess, inputs, outputs)
PredictedData[inds] = pose
batch_ind = 0
inds.clear()
batch_num += 1
else:
batch_ind += 1
elif counter >= nframes:
if batch_ind > 0:
pose = predict.getposeNP(
frames, dlc_cfg, sess, inputs, outputs
) # process the whole batch (some frames might be from previous batch!)
PredictedData[inds[:batch_ind]] = pose[:batch_ind]
break
counter += 1
pbar.close()
return PredictedData, nframes
def GetPoseS(cfg, dlc_cfg, sess, inputs, outputs, cap, nframes):
"""Non batch wise pose estimation for video cap."""
if cfg["cropping"]:
ny, nx = checkcropping(cfg, cap)
PredictedData = np.zeros(
(nframes, dlc_cfg["num_outputs"] * 3 * len(dlc_cfg["all_joints_names"]))
)
pbar = tqdm(total=nframes)
counter = 0
step = max(10, int(nframes / 100))
while cap.isOpened():
if counter != 0 and counter % step == 0:
pbar.update(step)
ret, frame = cap.read()
if ret:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
if cfg["cropping"]:
frame = img_as_ubyte(
frame[cfg["y1"] : cfg["y2"], cfg["x1"] : cfg["x2"]]
)
else:
frame = img_as_ubyte(frame)
pose = predict.getpose(frame, dlc_cfg, sess, inputs, outputs)
PredictedData[counter, :] = (
pose.flatten()
) # NOTE: thereby cfg['all_joints_names'] should be same order as bodyparts!
elif counter >= nframes:
break
counter += 1
pbar.close()
return PredictedData, nframes
def GetPoseS_GTF(cfg, dlc_cfg, sess, inputs, outputs, cap, nframes):
"""Non batch wise pose estimation for video cap."""
if cfg["cropping"]:
ny, nx = checkcropping(cfg, cap)
pose_tensor = predict.extract_GPUprediction(
outputs, dlc_cfg
) # extract_output_tensor(outputs, dlc_cfg)
PredictedData = np.zeros((nframes, 3 * len(dlc_cfg["all_joints_names"])))
pbar = tqdm(total=nframes)
counter = 0
step = max(10, int(nframes / 100))
while cap.isOpened():
if counter != 0 and counter % step == 0:
pbar.update(step)
ret, frame = cap.read()
if ret:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
if cfg["cropping"]:
frame = img_as_ubyte(
frame[cfg["y1"] : cfg["y2"], cfg["x1"] : cfg["x2"]]
)
else:
frame = img_as_ubyte(frame)
pose = sess.run(
pose_tensor,
feed_dict={inputs: np.expand_dims(frame, axis=0).astype(float)},
)
pose[:, [0, 1, 2]] = pose[:, [1, 0, 2]]
# pose = predict.getpose(frame, dlc_cfg, sess, inputs, outputs)
PredictedData[counter, :] = (
pose.flatten()
) # NOTE: thereby cfg['all_joints_names'] should be same order as bodyparts!
elif counter >= nframes:
break
counter += 1
pbar.close()
return PredictedData, nframes
def GetPoseF_GTF(cfg, dlc_cfg, sess, inputs, outputs, cap, nframes, batchsize):
"""Batchwise prediction of pose"""
PredictedData = np.zeros((nframes, 3 * len(dlc_cfg["all_joints_names"])))
batch_ind = 0 # keeps track of which image within a batch should be written to
batch_num = 0 # keeps track of which batch you are at
ny = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
nx = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
if cfg["cropping"]:
ny, nx = checkcropping(cfg, cap)
# Flip x, y, confidence and reshape
pose_tensor = predict.extract_GPUprediction(outputs, dlc_cfg)
pose_tensor = tf.gather(pose_tensor, [1, 0, 2], axis=1)
pose_tensor = tf.reshape(pose_tensor, (batchsize, -1))
frames = np.empty((batchsize, ny, nx, 3), dtype="ubyte")
pbar = tqdm(total=nframes)
counter = -1
inds = []
while cap.isOpened() and counter < nframes - 1:
ret, frame = cap.read()
counter += 1
if not ret:
warnings.warn(f"Could not decode frame #{counter}.")
continue
if cfg["cropping"]:
frame = img_as_ubyte(frame[cfg["y1"] : cfg["y2"], cfg["x1"] : cfg["x2"]])
else:
frame = img_as_ubyte(frame)
frames[batch_ind] = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
inds.append(counter)
if batch_ind == batchsize - 1:
pose = sess.run(pose_tensor, feed_dict={inputs: frames})
PredictedData[inds] = pose
batch_ind = 0
batch_num += 1
inds.clear()
pbar.update(batchsize)
else:
batch_ind += 1
if batch_ind > 0:
pose = sess.run(pose_tensor, feed_dict={inputs: frames})
PredictedData[inds[:batch_ind]] = pose[:batch_ind]
pbar.update(batch_ind)
pbar.close()
return PredictedData, nframes
def getboundingbox(x, y, nx, ny, margin):
x1 = max([0, int(np.amin(x)) - margin])
x2 = min([nx, int(np.amax(x)) + margin])
y1 = max([0, int(np.amin(y)) - margin])
y2 = min([ny, int(np.amax(y)) + margin])
return x1, x2, y1, y2
def GetPoseDynamic(
cfg, dlc_cfg, sess, inputs, outputs, cap, nframes, detectiontreshold, margin
):
"""Non batch wise pose estimation for video cap by dynamically cropping around previously detected parts."""
if cfg["cropping"]:
ny, nx = checkcropping(cfg, cap)
else:
ny, nx = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)), int(
cap.get(cv2.CAP_PROP_FRAME_WIDTH)
)
x1, x2, y1, y2 = 0, nx, 0, ny
detected = False
# TODO: perform detection on resized image (For speed)
PredictedData = np.zeros((nframes, 3 * len(dlc_cfg["all_joints_names"])))
pbar = tqdm(total=nframes)
counter = 0
step = max(10, int(nframes / 100))
while cap.isOpened():
if counter != 0 and counter % step == 0:
pbar.update(step)
ret, frame = cap.read()
if ret:
# print(counter,x1,x2,y1,y2,detected)
originalframe = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
if cfg["cropping"]:
frame = img_as_ubyte(
originalframe[cfg["y1"] : cfg["y2"], cfg["x1"] : cfg["x2"]]
)[y1:y2, x1:x2]
else:
frame = img_as_ubyte(originalframe[y1:y2, x1:x2])
pose = predict.getpose(frame, dlc_cfg, sess, inputs, outputs).flatten()
detection = np.any(pose[2::3] > detectiontreshold) # is anything detected?
if detection:
pose[0::3], pose[1::3] = (
pose[0::3] + x1,
pose[1::3] + y1,
) # offset according to last bounding box
x1, x2, y1, y2 = getboundingbox(
pose[0::3], pose[1::3], nx, ny, margin
) # coordinates for next iteration
if not detected:
detected = True # object detected
else:
if (
detected and (x1 + y1 + y2 - ny + x2 - nx) != 0
): # was detected in last frame and dyn. cropping was performed >> but object lost in cropped variant >> re-run on full frame!
# print("looking again, lost!")
if cfg["cropping"]:
frame = img_as_ubyte(
originalframe[cfg["y1"] : cfg["y2"], cfg["x1"] : cfg["x2"]]
)
else:
frame = img_as_ubyte(originalframe)
pose = predict.getpose(
frame, dlc_cfg, sess, inputs, outputs
).flatten() # no offset is necessary
x0, y0 = x1, y1
x1, x2, y1, y2 = 0, nx, 0, ny
detected = False
PredictedData[counter, :] = pose
elif counter >= nframes:
break
counter += 1
pbar.close()
return PredictedData, nframes
def AnalyzeVideo(
video,
DLCscorer,
DLCscorerlegacy,
trainFraction,
cfg,
dlc_cfg,
sess,
inputs,
outputs,
pdindex,
save_as_csv,
destfolder=None,
TFGPUinference=True,
dynamic=(False, 0.5, 10),
use_openvino="CPU" if is_openvino_available else None,
):
"""Helper function for analyzing a video."""
print("Starting to analyze % ", video)
if destfolder is None:
destfolder = str(Path(video).parents[0])
auxiliaryfunctions.attempt_to_make_folder(destfolder)
vname = Path(video).stem
try:
_ = auxiliaryfunctions.load_analyzed_data(destfolder, vname, DLCscorer)
except FileNotFoundError: