3D DeepLabCut Toolbox#
This notebook will highlight the functionality of the newly released 3D project option (as of 2.0.7+).
We recommend you look through these commands, and then you can easily modify this notebook for your own projects.
In summary, the new functionality will:
allow you to calibrate your cameras using checkerboard images
compute and fix camera distortions
convert your 2D DeepLabCut tracking to 3D
allow for plotting in 3D space
Create a New 3D Project:#
You will run this first function one time per project; a project is defined as a given set of cameras and calibration images. You can always analyze new videos within this project.
The function create_new_project_3d creates a new project directory specifically for converting the 2D pose to 3D pose, required subdirectories, and a basic 3D project configuration file. Each project is identified by the name of the project (e.g. Task1), name of the experimenter (e.g. YourName), as well as the date at creation.
Thus, this function requires the user to input the enter the name of the project, the name of the experimenter and number of cameras to be used. Currently, DeepLabCut supports triangulation using 2 cameras, but will expand to more than 2 cameras in a future version.
Optional arguments specify the working directory, i.e. where the project directory will be created. If the optional argument working_directory is unspecified, the project directory is created in the current working directory. Please note that the Full path of the 3D project configuration file will be referenced as config_path3d
.
NOTE: Be sure you are inside your DLC anaconda environment!
import deeplabcut
#Setup your project variables:
YourName = 'teamDLC'
YourExperimentName = 'testing'
config_path = deeplabcut.create_new_project_3d(YourExperimentName,YourName,num_cameras=2)
Created "/home/mackenzie/Desktop/DeepLabCut2.0-2.2/examples/testing-teamDLC-2019-10-29-3d/camera_matrix"
Created "/home/mackenzie/Desktop/DeepLabCut2.0-2.2/examples/testing-teamDLC-2019-10-29-3d/calibration_images"
Created "/home/mackenzie/Desktop/DeepLabCut2.0-2.2/examples/testing-teamDLC-2019-10-29-3d/undistortion"
Created "/home/mackenzie/Desktop/DeepLabCut2.0-2.2/examples/testing-teamDLC-2019-10-29-3d/corners"
Generated "/home/mackenzie/Desktop/DeepLabCut2.0-2.2/examples/testing-teamDLC-2019-10-29-3d/config.yaml"
A new project with name testing-teamDLC-2019-10-29-3d is created at /home/mackenzie/Desktop/DeepLabCut2.0-2.2/examples and a configurable file (config.yaml) is stored there. If you have not calibrated the cameras, then use the function 'calibrate_camera' to start calibrating the camera otherwise use the function ``triangulate`` to triangulate the dataframe
TIP 1: you can also pass working_directory='Full path of the working directory'
if you want to place this folder somewhere beside the current directory you are working in.
TIP 2: you can also place config_path3d in front of deeplabcut.create_new_project_3d to create a variable that holds the path to the config.yaml file, i.e. config_path3d=deeplabcut.create_new_project_3d(...
#If you're loading an already created project, just set the 3D Project config_path variable:
#import os
#from pathlib import Path
#config_path3d = os.path.join(os.getcwd(),'testing3D-DeepLabCutTeam-2019-06-05-3d/config.yaml')
#print(config_path3d)
Calibrate your cameras!#
(CRITICAL!) You must take images of a checkerboard to calibrate your images. Here are example boards you could print and use (mount them on a flat, hard surface!): https://markhedleyjones.com/projects/calibration-checkerboard-collection.
You must save the image pairs as .jpg files.
They should be named with the camera-# as the prefix, i.e. camera-1-01.jpg and camera-2-01.jpg for the first pair of images.
While taking the images:
Keep the orientation of the chessboard same and do not rotate more than 30 degrees. Rotating the chessboard circular will change the origin across the frames and may result in incorrect order of detected corners.
Cover several distances, and within each distance, cover all parts of the image view (all corners and center).
Use a checkerboard as big as possible, ideally with at least 8x6 squares.
Aim for taking at least 70 pair of images as after corner detection, some of the images might need to be discarded due to either incorrect corner detection or incorrect order of detected corners.
DEMO images:#
Here, we used a standard set along with this notebook. These images are a part of the Camera Calibration ToolBox for Matlab; specifically example 5. The images can be downloaded at: https://data.caltech.edu/records/20164. After downloading, the calibration images can be found at ../calib_doc/htmls/calib_example.zip
If you wish to run this DEMO notebook, download the files and place inside the calibration_images directory. (To note, pairs 1 and 6 are not detected correctly, so please delete these images!).
When acquiring calibration images from your own setup, it is recommended to take multiple pairs of image (around 50-70 pairs!).
The camera calibration is an iterative process, where the user needs to select a set of calibration images where the grid pattern is correctly detected. The function:deeplabcut.calibrate_cameras(config_path)
extracts the grid pattern from the calibration images and store them under the corners
directory. The grid pattern could be 8x8 or 5x5 etc. We use a pattern of the 8x6 grid to find the internal corners of the checkerboard.
In some cases, it may happen that the corners are not detected correctly or the order of corners detected in the camera-1 image and camera-2 image is incorrect. We need to remove these pair of images as they will reduce the calibration accuracy.
NEXT/if not done: please place your (or demo) images into the calibration_images directory.
Edit the config.yaml file:#
change the camera names; i.e. if you do “”cam1, cam2””, or “camera-1, camera-2”, or “left, right”, etc.
Note, that once this is set, you cannot edit these (they are used for other steps).
deeplabcut.calibrate_cameras(config_path3d, cbrow =9,cbcol =6,calibrate=False,alpha=0.9)
NOTE: you need to specify how many rows (cbrow
) and columns (cbcol
) your checkerboard has (i.e. the intersection points - see demo images if unclear). Also, first set the variable calibrate
to False, so you can remove any faulty images. You need to visually inspect the output to check for the detected corners and select those pair of images where the corners are correctly detected.
Once all the set of images are selected (namely, delete from the folder any bad pairs!) where the corners and their orders are detected correctly, then the two cameras can be calibrated using:
They will look like this (one example frame):
deeplabcut.calibrate_cameras(config_path3d, cbrow = 9,cbcol = 6, calibrate=True, alpha=0.9)
Check for Undistortion:#
In order to check how well the stereo calibration is, it is recommended to undistort the calibration images and the corner points using camera matrices and project these undistorted points on the undistorted images to check if they align correctly. This can be done in deeplabcut as:
import matplotlib
%matplotlib inline
deeplabcut.check_undistortion(config_path3d)
Each calibration image is undistorted and saved under the directory undistortion
. A plot with a pair of undistorted camera images with its undistorted corner points overlaid is also stored. Please visually inspect this image. All the undistorted corner points from all the calibration images are triangulated and plotted for the user to visualize for any undistortion related errors. If they are not correct, go check and revise the calibration images (then repeat the calirbation and this step)!
Triangulation –> converting your 2D to 3D!#
If there are no errors in the undistortion, then the pose from the 2 cameras can be triangulated to get the 3D DeepLabCut coordinates!
(CRITICAL!) Name the video files in such a way that the file name contains the name of the cameras as specified in the config file
. e.g. if the cameras as named as camera-1
and camera-2
(or cam-1
, cam-2
etc.) then the video filename must contain this naming, i.e. this could be named as rig-1-mouse-day1-camera-1.avi
and rig-1-mouse-day1-camera-2.avi
. Notably, the videos do not need to be the same pixel size, but be sure they are similar in size to the calibration images (and they must be the same cameras used for calibration).
(CRITICAL!) Edit the config.yaml file:#
You must also edit the 3D project config.yaml file to denote which DeepLabCut projects have the information for the 2D views.
Of critical importance is that you need to input the same body part names as in the config.yaml file of the 2D project.
You must set the snapshot to use inside the 2D config file (default is -1, namely the last training snapnot of the network).
You need to set a “scorer 3D” name; this will point to the project file and be set in future 3D output file names.
You should define a “skeleton” here as well (note, this is not rigid, it just connects the points in the plotting step). Not every point needs to be “skeletonized”, i.e. these points can be a subset of the full body parts list. The other points will just be plotted into the 3D space.
Next, pass the config_path3d
and now the video_path
, which is the path to the folder where all the videos from two cameras are stored. The triangulation can be done in deeplabcut by typing:
# Of course, this does not work on the demo calibration images,
# but when you are ready for your own dataset, edit and then run the following!
video_path = '/home/yourname/videoFolder'
deeplabcut.triangulate(config_path3d,video_path, videotype='mp4')
The triangulated file is now saved under the same directory where the video files reside (or you passed a destination folder path)! These files can now be used for future analysis. This step can now be run at anytime as you collect new videos, and easily added to your automated analysis pipeline, i.e. such as usingdeeplabcut.triangulate(config_path3d, video_path)
instead of deeplabcut.analyze_videos
Visualize your 3D DeepLabCut Videos:#
In order to visualize the pose in 3D, the user can create a 3D video for certain frames (these are large files, so we advise just looking at a subset of frames). The user can specify the path of the triangulated file and specify the start and end frame indices to create a 3D labeled video. Note that the triangulated_file is the newly created file that ends with yourDLC_3D_scorername.h5. This can be done using:
deeplabcut.create_labeled_video_3d(config_path,['triangulated_file_folder'],start=50,end=250, trailpoints=3)