How to get accurate measurement of the objects?
Describe the bug Goal: I am trying to build up the code that measures the length of the object of interest. I assume this is achievable since I observed that the 3D mode in k4aviewer has a fairly clear visualization of the 3D point cloud.
My approaches First I capture the color and depth image using Azure Kinect, then the color image will be fed into a pre-trained neural network for object detection. The output of this neural network will be the coordination of the points of interest. Next the coordination of points will be fed back into the Azure Kinect SDK to identify the 3D point cloud coordinate x, y and z. The final step is to find the distance/length/dimension of those 3D coordinates x y and z.
However, there is a huge error of the dimension of the object computed from the x y and z values returned by Azure Kinect using my code. I highly doubt that my code and approach are missing some key steps. Maybe the error results from missing calibration info or inaccuracy of the depth values for 2D coordinate points. Any help much appreciated!
Question
I noticed that in the example code provided here https://github.com/microsoft/Azure-Kinect-Sensor-SDK/blob/develop/examples/fastpointcloud/main.cpp
the function
k4a_calibration_2d_to_3d(calibration, &p, 1.f, K4A_CALIBRATION_TYPE_DEPTH, K4A_CALIBRATION_TYPE_DEPTH, &ray, &valid);
takes the input 1.f as the depth_value argument. But here 1.f is not the actual depth value. I am wondering whether the accuracy will be improved or not by providing the approximated depth value obtained from the transformed depth image to replace this 1.f.
To Reproduce
- Capture the color and depth image;
- Transform the depth image to the color camera;
- For simplicity, here I manually find the coordinate of points of interest from the color image.
- Get the corresponding depth values of those points from the transformed depth image. (Notice that it is possible the depth value returned from the transformed depth image could be 0, here I add a trivial filtering function called average_window_filter, which generates a small window around the point and get the average of the depth values of the points in that window.)
- Get the 3D coordinates of the points.
Here I also append my code:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <k4a/k4a.h>
#include <k4a/k4atypes.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <direct.h>
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/opencv.hpp"
#include <opencv2/photo/photo.hpp>
#include <opencv2/core/mat.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d.hpp>
#include <math.h>
#include <string>
#include <fstream>
#include <sstream>
using namespace cv;
using namespace std;
int average_window_filter(const Mat trans_depth_image, int i, int j, int height, int width)
{
bool found = false;
int window_size = 1;
float depth = 0;
while (found == false)
{
window_size *= 2;
int step = window_size / 2;
int x_lower = max(i - step, 0);
int x_upper = min(i + step, height);
int y_lower = max(j - step, 0);
int y_upper = min(j + step, width);
int value = 0;
int number = 0;
for (int x = x_lower; x < x_upper; x++)
{
for (int y = y_lower; y < y_upper; y++)
{
if (trans_depth_image.at<cv::int16_t>(x, y) > 0)
{
found = true;
value += trans_depth_image.at<cv::int16_t>(x, y);
number += 1;
}
}
}
if (found == true)
{
depth = value / number;
}
}
return depth;
}
static void convert_2d_depth_to_3d_point_cloud(const k4a_calibration_t* calibration, const Mat trans_depth_image, float coordinate_x, float coordinate_y)
{
int width = calibration->color_camera_calibration.resolution_width;
printf("width = %d", width);
int height = calibration->color_camera_calibration.resolution_height;
printf("height = %d", height);
int valid;
float depth;
int coordinate_x_int = static_cast<int>(coordinate_x);
int coordinate_y_int = static_cast<int>(coordinate_y);
depth = average_window_filter(trans_depth_image, coordinate_x_int, coordinate_y_int, height, width);
k4a_float3_t ray;
k4a_float2_t point_2d;
point_2d.xy.x = coordinate_x;
point_2d.xy.y = coordinate_y;
k4a_calibration_2d_to_3d(calibration, &point_2d, depth, K4A_CALIBRATION_TYPE_DEPTH, K4A_CALIBRATION_TYPE_DEPTH, &ray, &valid);
cout << "x = " << ray.xyz.x << " | y = " << ray.xyz.y << " | z = " << ray.xyz.z << endl;
}
int main()
{
// Start by counting the number of connected devices
uint32_t device_count = k4a_device_get_installed_count();
if (device_count == 0)
{
printf("No K4A devices found\n");
return 0;
}
else
{
printf("Found %d connected devices:\n", device_count);
}
// Define the Exit block
int returnCode = 1;
// Initialize the the device and capture attributes
k4a_device_t device = NULL;
k4a_capture_t capture = NULL;
const int32_t TIMEOUT_IN_MS = 1000;
// Initialize the frame count
int totalFrame = 1;
int captureFrameCount = totalFrame;
printf("Capturing %d frames\n", captureFrameCount);
// Set the configuration of device, you can also set it after open the device but before starting the camera
k4a_device_configuration_t config = K4A_DEVICE_CONFIG_INIT_DISABLE_ALL;
config.color_format = K4A_IMAGE_FORMAT_COLOR_BGRA32; // <==== For Color image
config.color_resolution = K4A_COLOR_RESOLUTION_2160P;
config.depth_mode = K4A_DEPTH_MODE_NFOV_UNBINNED; // <==== For Depth image
config.camera_fps = K4A_FRAMES_PER_SECOND_30;
config.synchronized_images_only = true;
// Open the device
if (K4A_RESULT_SUCCEEDED != k4a_device_open(K4A_DEVICE_DEFAULT, &device))
{
printf("Failed to open device\n");
goto Exit;
}
// Set the calibration
k4a_calibration_t calibration;
if (K4A_RESULT_SUCCEEDED !=
k4a_device_get_calibration(device, config.depth_mode, config.color_resolution, &calibration))
{
printf("Failed to get calibration\n");
goto Exit;
}
// Start the camera
if (K4A_RESULT_SUCCEEDED != k4a_device_start_cameras(device, &config))
{
printf("Failed to start device\n");
goto Exit;
}
// Start to receive the captures and framess
while (captureFrameCount-- > 0)
{
// Get a depth frame
switch (k4a_device_get_capture(device, &capture, TIMEOUT_IN_MS))
{
case K4A_WAIT_RESULT_SUCCEEDED:
break;
case K4A_WAIT_RESULT_TIMEOUT:
printf("Timed out waiting for a capture\n");
continue;
break;
case K4A_WAIT_RESULT_FAILED:
printf("Failed to read a capture\n");
goto Exit;
}
// Probe for a color image
k4a_image_t image_color = k4a_capture_get_color_image(capture);
if (image_color != NULL)
{
// Get the sizes of color image
int width = k4a_image_get_width_pixels(image_color);
int height = k4a_image_get_height_pixels(image_color);
int strides = k4a_image_get_stride_bytes(image_color);
printf("Color image height, width and strides: %d, %d, %d\n", height, width, strides);
// Store the image using opencv Mat
uint8_t* color_image_data = k4a_image_get_buffer(image_color);
const Mat color_image(height, width, CV_8UC4, (void*)color_image_data, Mat::AUTO_STEP);
// Display the images
namedWindow("foobar", WINDOW_AUTOSIZE);
imshow("foobar", color_image);
waitKey(1000);
}
else
{
printf(" | Color None ");
}
// Probe for a depth16 image
const k4a_image_t image_depth = k4a_capture_get_depth_image(capture);
if (image_depth != NULL)
{
// Get the sizes of depth image
int width = k4a_image_get_width_pixels(image_depth);
int height = k4a_image_get_height_pixels(image_depth);
int strides = k4a_image_get_stride_bytes(image_depth);
printf("Depth image height, width and strides: %d, %d, %d\n", height, width, strides);
// Store the image using opencv Mat
uint16_t* depth_image_data = (uint16_t*)(void*)k4a_image_get_buffer(image_depth);
const Mat depth_image(height, width, CV_16U, (void*)depth_image_data, Mat::AUTO_STEP);
// Display the images
namedWindow("foobar", WINDOW_AUTOSIZE);
imshow("foobar", depth_image);
waitKey(1000);
}
else
{
printf(" | Depth16 None\n");
}
// 9.2 derive the depth value in the color camera geometry using the function k4a_transformation_depth_image_to_color_camera().
k4a_transformation_t transformation = NULL;
k4a_image_t transformed_depth_image = NULL;
int width = k4a_image_get_width_pixels(image_color);
int height = k4a_image_get_height_pixels(image_color);
if (K4A_RESULT_SUCCEEDED != k4a_image_create(K4A_IMAGE_FORMAT_DEPTH16,
width,
height,
width * (int)sizeof(uint16_t),
&transformed_depth_image))
{
printf("Failed to create transformed color image\n");
return false;
}
else
{
// Transform the depth image to the size of color camera
transformation = k4a_transformation_create(&calibration);
k4a_transformation_depth_image_to_color_camera(transformation, image_depth, transformed_depth_image);
// Store the image using opencv Mat
uint16_t* transformed_depth_image_data = (uint16_t*)(void*)k4a_image_get_buffer(transformed_depth_image);
const Mat trans_depth_image(height, width, CV_16U, (void*)transformed_depth_image_data, Mat::AUTO_STEP);
// Display the transformed depth images
namedWindow("foobar", WINDOW_AUTOSIZE);
imshow("foobar", trans_depth_image);
waitKey(1000);
// Find the point xy coordinate from color image, this pair of points belongs to the short edge of the shelf
float point1_row = (height / 2) * 3.7 / 8.9;
float point1_column = (width / 2) * 6.3 / 15.95;
convert_2d_depth_to_3d_point_cloud(&calibration, trans_depth_image, point1_row, point1_column);
float point2_row = (height / 2) * 3.8 / 8.9;
float point2_column = (width / 2) * 8.6 / 15.95;
convert_2d_depth_to_3d_point_cloud(&calibration, trans_depth_image, point2_row, point2_column);
float point3_row = (height / 2) * 4.8 / 8.9;
float point3_column = (width / 2) * 10.6 / 15.95;
convert_2d_depth_to_3d_point_cloud(&calibration, trans_depth_image, point3_row, point3_column);
float point4_row = (height / 2) * 5.1 / 8.9;
float point4_column = (width / 2) * 24.85 / 15.95;
convert_2d_depth_to_3d_point_cloud(&calibration, trans_depth_image, point4_row, point4_column);
}
// release images
k4a_image_release(image_depth);
k4a_image_release(image_color);
k4a_image_release(transformed_depth_image);
// release capture
k4a_capture_release(capture);
}
returnCode = 0;
Exit:
if (device != NULL)
{
k4a_device_stop_cameras(device);
k4a_device_close(device);
}
return returnCode;
}
Expected behavior Return accurate 3D point coordinates.
Logs
Screenshots
I also append the color & depth & transformed depth images here. Notice that there will be two while lines in the color image which describe the object I would like to measure. The first pair is on the top of the left shelf. The second pair is at the intersection of ceiling and purple wall. The center point of the image is captured by a small white circle.
color image:

depth image:

transformed depth image:

Result:

Desktop (please complete the following information):
- OS with Version: Windows 10
- SDK Version: 1.2.0
- Firmware version: N/A
@opalmu thanks for sharing the code and I like your idea for this project. And I think you have the right idea for the pipeline, there are few issues in your code that I notice and some of my comments hope they helps:
- First issue is inside the function convert_2d_depth_to_3d_point_cloud, you call the k4a_calibration_2d_to_3d with passing the source camera and target camera with K4A_CALIBRATION_TYPE_DEPTH, this is incorrect, because you already transformed the depth image into the color image before this. You should use K4A_CALIBRATION_TYPE_COLOR for both source and source
- Second issue you should enhance is, it is always a good practice to check the return result of the k4a_calibration_2d_to_3d as well as the valid parameters to determine whether you had a valid unproject point before using it. Please refer to the API doc for this function.
With above two suggestions, try this snippet in your convert_2d_depth_to_3d_point_cloud function:
point_2d.xy.x = coordinate_x;
point_2d.xy.y = coordinate_y;
if (K4A_RESULT_SUCCEEDED == k4a_calibration_2d_to_3d(calibration, &point_2d, depth, K4A_CALIBRATION_TYPE_COLOR, K4A_CALIBRATION_TYPE_COLOR, &ray, &valid))
{
cout << "x = " << ray.xyz.x << " | y = " << ray.xyz.y << " | z = " << ray.xyz.z << " | depth = " << depth << " | valid = " << valid << endl;
}
else
{
cout << "k4a_calibration_2d_to_3d failed for the current input pixel!" << endl;
}
- another comment is, understand that you may see 0 depth value in the transformed image, for your scenario, I think you have 2 options:
- you can either just return fail if you see such a 0 depth value, then since your goal is to measure the object size, therefore, you possible can move the camera during running your program, then it is possible that you will get a non-zero depth when you move the camera at certain frame and generate the result
- if you really want to do the average filter, there is a possibility that you have some depth discontinuity in your searching window, and you may ended with an average depth quite wrong if the discontinuity is large. therefore, you should take this into account in your program (e.g. some threshold of the depth value variation in the window)
Let us know whether this answered your questions.
@ rabbitdaxi Thanks for your really helpful comments! I modify the code based on your comments and the result is really nice.
The wall I tried to measure has the actual length as 4.699 meters (given by laser), and the computed length based on 3D coordinates returned by Kinect is 4.708.
It is pretty impressive to achieve millimeter accuracy considering the fact that the points are detected manually and the filter method I used is not very good actually. I am still using my own trivial average window filter function which satisfies my need for now. Taking too many images to find the actual depth value may increase the computational cost for my neural network model substantially.
Really appreciate your help!
@opalmu Happy to see your application works well and thanks for the confirmation on the accurate measurement because of the depth camera accuracy.
@opalmu Hi! How is your project going? I am working on a project and it is very similar to your idea. I need to use the Azure Camera to measure the dimension of the objects. However, I have no experience of programming and it's so hard for me to create and modify my own code. Can I use your code? I appreciate!
@opalmu Which I interested is the last step you have mentioned. How to using the cloud points find the distance/length/dimension. Can you described how does you complete this step?
I have understand this function. It is the inner function with the device. and it can transform image position(in pixel) to camera position(world coordinate in millimeter based on color camera or depth camer). With that, @opalmu recognize the object in color image, and transform the position to world coordinate with function k4a_calibration_2d_to_3d. by the way, you should be careful of the Parameters.
I have been trying to do something very similar to the above task. I used OpenCV's mouse callback to pick two points and tried to get their distance. In the process, I didn't get as good measurement of distance between two points as said here and I was getting valid=0 at points where I would expect a valid transformation. Upon overlaying the depth image with color image and visualizing the points where the depth reading is zero, I got it looking like untransformed.
Here's the code I used to paint the color image black for spots where the depth readings are:
transformation = k4a_transformation_create(&calibration);
k4a_transformation_depth_image_to_color_camera(transformation, image_depth, transformed_depth_image);
// Store the image using opencv Mat
uint16_t* transformed_depth_image_data = (uint16_t*)(void*)k4a_image_get_buffer(transformed_depth_image);
const Mat trans_depth_image(height, width, CV_16U, (void*)transformed_depth_image_data, Mat::AUTO_STEP);
Mat valid_color_img = color_image.clone();
for (int i=0; i<height; i++){
for (int j=0; j<width; j++){
if (trans_depth_image.at<cv::int16_t>(i, j) == 0){
// cout <<" The depth pixel value at " <<i <<" and " << j << " is " << val << endl;
// cout << "Replacing pixel" << endl;
valid_color_img.at<Vec3b>(Point(j, i))[0] = 0;
valid_color_img.at<Vec3b>(Point(j, i))[1] = 0;
valid_color_img.at<Vec3b>(Point(j, i))[2] = 0;
}
}
}
And here's the image output:

Surely I must have been missing something. Can someone point it and explain the right way to achieve what I am trying in this code?