Autonomy Software C++ 24.5.1
Welcome to the Autonomy Software repository of the Mars Rover Design Team (MRDT) at Missouri University of Science and Technology (Missouri S&T)! API reference contains the source code and other resources for the development of the autonomy software for our Mars rover. The Autonomy Software project aims to compete in the University Rover Challenge (URC) by demonstrating advanced autonomous capabilities and robust navigation algorithms.
Loading...
Searching...
No Matches
DepthMeasureEncodeDecode.hpp File Reference

This file implements the H264 encoding and decoding of depth measures. More...

#include "../../../src/util/ExampleChecker.h"
Include dependency graph for DepthMeasureEncodeDecode.hpp:

Go to the source code of this file.

Functions

void OriginalDepthMouseCallback (int nEvent, int nX, int nY, int nFlags, void *pUserData)
 This is a mouse callback function that will be called when the user clicks on the original depth image. It will print the original depth value at the clicked pixel location.
void DecodedDepthMouseCallback (int nEvent, int nX, int nY, int nFlags, void *pUserData)
 This is a mouse callback function that will be called when the user clicks on the decoded depth image. It will print the decoded depth value at the clicked pixel location.
void RunExample ()
 This will implement the H264 encoding and decoding of depth measures discussed in this paper: 2011-Adapting-Standard-Video-Codecs-for-Depth-Streaming.

Detailed Description

This file implements the H264 encoding and decoding of depth measures.

Author
clayjay3 (clayt.nosp@m.onra.nosp@m.ycowe.nosp@m.n@gm.nosp@m.ail.c.nosp@m.om)
Date
2025-04-21

Function Documentation

◆ OriginalDepthMouseCallback()

void OriginalDepthMouseCallback ( int nEvent,
int nX,
int nY,
int nFlags,
void * pUserData )

This is a mouse callback function that will be called when the user clicks on the original depth image. It will print the original depth value at the clicked pixel location.

Parameters
nEvent- The type of mouse event (e.g., left button click).
nX- The x-coordinate of the mouse event.
nY- The y-coordinate of the mouse event.
nFlags- The flags associated with the mouse event.
pUserData- Pointer to user data (in this case, the original depth image).
Author
clayjay3 (clayt.nosp@m.onra.nosp@m.ycowe.nosp@m.n@gm.nosp@m.ail.c.nosp@m.om)
Date
2025-04-22
45{
46 (void) nFlags; // Unused parameter
47 if (nEvent != cv::EVENT_LBUTTONDOWN)
48 return;
49
50 cv::Mat* cvDepthImage = static_cast<cv::Mat*>(pUserData);
51 if (nX >= 0 && nY >= 0 && nX < cvDepthImage->cols && nY < cvDepthImage->rows)
52 {
53 uint16_t unDepthValue = cvDepthImage->at<uint16_t>(nY, nX);
54 std::cout << "Original depth at (" << nX << ", " << nY << "): " << unDepthValue << " units" << std::endl;
55 }
56}
_Tp & at(int i0=0)
int rows
int cols
EVENT_LBUTTONDOWN
::uint16_t uint16_t
Here is the call graph for this function:
Here is the caller graph for this function:

◆ DecodedDepthMouseCallback()

void DecodedDepthMouseCallback ( int nEvent,
int nX,
int nY,
int nFlags,
void * pUserData )

This is a mouse callback function that will be called when the user clicks on the decoded depth image. It will print the decoded depth value at the clicked pixel location.

Parameters
nEvent- The type of mouse event (e.g., left button click).
nX- The x-coordinate of the mouse event.
nY- The y-coordinate of the mouse event.
nFlags- The flags associated with the mouse event.
pUserData- Pointer to user data (in this case, the decoded depth image).
Author
clayjay3 (clayt.nosp@m.onra.nosp@m.ycowe.nosp@m.n@gm.nosp@m.ail.c.nosp@m.om)
Date
2025-04-22
73{
74 (void) nFlags; // Unused parameter
75 if (nEvent != cv::EVENT_LBUTTONDOWN)
76 return;
77
78 cv::Mat* cvDepthImage = static_cast<cv::Mat*>(pUserData);
79 if (nX >= 0 && nY >= 0 && nX < cvDepthImage->cols && nY < cvDepthImage->rows)
80 {
81 uint16_t unDepthValue = cvDepthImage->at<uint16_t>(nY, nX);
82 std::cout << "Decoded depth at (" << nX << ", " << nY << "): " << unDepthValue << " units" << std::endl;
83 }
84}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ RunExample()

void RunExample ( )

This will implement the H264 encoding and decoding of depth measures discussed in this paper: 2011-Adapting-Standard-Video-Codecs-for-Depth-Streaming.

Author
clayjay3 (clayt.nosp@m.onra.nosp@m.ycowe.nosp@m.n@gm.nosp@m.ail.c.nosp@m.om)
Date
2025-04-21
96{
97 // Encoding constants.
98 const float fW = 65536.0f; // Maximum depth value.
99 const float fNP = 512.0f; // Number of depth levels.
100 const int nH264CompressionLevel = 10; // H264 compression level. 0-51 Lower is better quality
101
103 // Create a fake depth measure.
105 // Create a cv::Mat to store the 16-bit depth measure.
106 cv::Mat cvDepthMeasure(720, 1280, CV_16UC1, cv::Scalar(0));
107 // Fill the depth measure with values of fW - 1 at each pixel.
108 for (int nY = 0; nY < cvDepthMeasure.rows; ++nY)
109 {
110 for (int nX = 0; nX < cvDepthMeasure.cols; ++nX)
111 {
112 cvDepthMeasure.at<uint16_t>(nY, nX) = static_cast<uint16_t>(fW - 1);
113 }
114 }
115
116 // Add shapes at different depths.
117 cv::RNG RNG(12345); // Random number generator with seed.
118 // Add 10 circles.
119 for (int nI = 0; nI < 10; ++nI)
120 {
121 int nCenterX = RNG.uniform(50, cvDepthMeasure.cols - 50);
122 int nCenterY = RNG.uniform(50, cvDepthMeasure.rows - 50);
123 int nRadius = RNG.uniform(30, 100);
124 uint16_t unDepth = static_cast<uint16_t>(RNG.uniform(5000, 60000));
125
126 for (int nY = nCenterY - nRadius; nY <= nCenterY + nRadius; ++nY)
127 {
128 if (nY < 0 || nY >= cvDepthMeasure.rows)
129 continue;
130
131 for (int nX = nCenterX - nRadius; nX <= nCenterX + nRadius; ++nX)
132 {
133 if (nX < 0 || nX >= cvDepthMeasure.cols)
134 continue;
135
136 if ((nX - nCenterX) * (nX - nCenterX) + (nY - nCenterY) * (nY - nCenterY) <= nRadius * nRadius)
137 {
138 cvDepthMeasure.at<uint16_t>(nY, nX) = unDepth;
139 }
140 }
141 }
142 }
143 // Add 8 squares.
144 for (int nI = 0; nI < 8; ++nI)
145 {
146 int nCenterX = RNG.uniform(50, cvDepthMeasure.cols - 50);
147 int nCenterY = RNG.uniform(50, cvDepthMeasure.rows - 50);
148 int nSize = RNG.uniform(30, 100);
149 uint16_t unDepth = static_cast<uint16_t>(RNG.uniform(5000, 60000));
150
151 for (int nY = nCenterY - nSize / 2; nY <= nCenterY + nSize / 2; ++nY)
152 {
153 if (nY < 0 || nY >= cvDepthMeasure.rows)
154 continue;
155
156 for (int nX = nCenterX - nSize / 2; nX <= nCenterX + nSize / 2; ++nX)
157 {
158 if (nX < 0 || nX >= cvDepthMeasure.cols)
159 continue;
160 cvDepthMeasure.at<uint16_t>(nY, nX) = unDepth;
161 }
162 }
163 }
164 // Add 6 triangles.
165 for (int nI = 0; nI < 6; ++nI)
166 {
167 int nCenterX = RNG.uniform(50, cvDepthMeasure.cols - 50);
168 int nCenterY = RNG.uniform(50, cvDepthMeasure.rows - 50);
169 int nSize = RNG.uniform(40, 120);
170 uint16_t unDepth = static_cast<uint16_t>(RNG.uniform(5000, 60000));
171
172 // Define triangle vertices.
173 cv::Point aVertices[3] = {cv::Point(nCenterX, nCenterY - nSize / 2),
174 cv::Point(nCenterX - nSize / 2, nCenterY + nSize / 2),
175 cv::Point(nCenterX + nSize / 2, nCenterY + nSize / 2)};
176
177 // Fill the triangle.
178 cv::fillConvexPoly(cvDepthMeasure, aVertices, 3, cv::Scalar(unDepth));
179 }
180
182 // Encode the depth measure.
184 // Create a image to store the encoded depth measure.
185 cv::Mat cvEncodedDepth(cvDepthMeasure.rows, cvDepthMeasure.cols, CV_8UC3, cv::Scalar(0));
186 // Encode each pixel in the depth measure.
187 for (int nY = 0; nY < cvDepthMeasure.rows; ++nY)
188 {
189 for (int nX = 0; nX < cvDepthMeasure.cols; ++nX)
190 {
191 // Get the depth value.
192 // uint16_t unDepthVal = cvDepthMeasure.at<uint16_t>(nY, nX);
193 uint16_t unDepthVal = 2000;
194
195 // Normalize the depth value.
196 float fNormalizedDepth = (unDepthVal + 0.5f) / fW;
197
198 // Period for triangle waves.
199 float fP = fNP / fW;
200
201 // L(d): Linear mapping for low-resolution depth.
202 float fL = fNormalizedDepth;
203
204 // H_a(d): Triangle wave function 1.
205 float fHa = fmod(fL / (fP / 2.0f), 2.0f);
206 fHa = fHa <= 1.0f ? fHa : 2.0f - fHa;
207
208 // H_b(d): Triangle wave function 2 (phase-shifted by π/4).
209 float fHb = fmod((fL - (fP / 4.0f)) / (fP / 2.0f), 2.0f);
210 fHb = fHb <= 1.0f ? fHb : 2.0f - fHb;
211
212 // Scale values to 0-255 range for 8-bit storage
213 uchar unY = static_cast<uchar>(fL * 255.0f);
214 uchar unU = static_cast<uchar>(fHa * 255.0f);
215 uchar unV = static_cast<uchar>(fHb * 255.0f);
216
217 // Assign encoded values to output image.
218 cvEncodedDepth.at<cv::Vec3b>(nY, nX) = cv::Vec3b(unY, unU, unV);
219 }
220 }
221
222 // Use ffmpeg to emulate the H264 encoding.
223 // Save the encoded depth to a temporary file
224 std::string szInputFilename = "temp_encoded_depth.png";
225 std::string szH264Filename = "temp_h264.mp4";
226 std::string szOutputFilename = "temp_decoded_depth.png";
227
228 // Save original encoded depth image.
229 if (!cv::imwrite(szInputFilename, cvEncodedDepth))
230 {
231 std::cerr << "Failed to save encoded depth image to " << szInputFilename << std::endl;
232 }
233 std::cout << "Simulating H264 encoding/decoding with ffmpeg..." << std::endl;
234
235 // Keep a copy of the pre-H264 encoded depth for comparison.
236 cv::Mat cvPreH264Depth = cvEncodedDepth.clone();
237
238 // Build the ffmpeg commands with appropriate options for depth data.
239 // Using higher quality (lower CRF) to preserve depth information. CRF range is 0-51, where lower is better quality.
240 std::string szEncoderCMD = "ffmpeg -y -i " + szInputFilename + " -c:v libx264 -preset fast -tune zerolatency -crf " + std::to_string(nH264CompressionLevel) + " " +
241 szH264Filename + " 2>/dev/null";
242
243 std::string szDecoderCMD = "ffmpeg -y -i " + szH264Filename + " -frames:v 1 " + szOutputFilename + " 2>/dev/null";
244
245 // Run encoder and decoder.
246 int nEncoderResult = system(szEncoderCMD.c_str());
247 if (nEncoderResult != 0)
248 {
249 std::cerr << "Error running ffmpeg encoder. Make sure ffmpeg is installed." << std::endl;
250 }
251
252 int nDecoderResult = system(szDecoderCMD.c_str());
253 if (nDecoderResult != 0)
254 {
255 std::cerr << "Error running ffmpeg decoder." << std::endl;
256 }
257
258 // Read the H264-processed image back.
259 cv::Mat cvH264ProcessedDepth = cv::imread(szOutputFilename);
260 if (cvH264ProcessedDepth.empty())
261 {
262 std::cerr << "Error reading H264-processed depth image" << std::endl;
263 }
264 else
265 {
266 // Display both versions for comparison.
267 cv::imshow("Pre-H264 Encoded Depth", cvPreH264Depth);
268 cv::imshow("Post-H264 Encoded Depth", cvH264ProcessedDepth);
269 cv::waitKey(500); // Short pause to ensure images are displayed.
270
271 // Replace the original encoded depth with the H264-processed version.
272 cvEncodedDepth = cvH264ProcessedDepth;
273
274 std::cout << "H264 encoding/decoding simulation complete" << std::endl;
275 }
276
277// Clean up temporary files.
278#ifdef _WIN32
279 system(("del " + szInputFilename + " " + szH264Filename + " " + szOutputFilename).c_str());
280#else
281 system(("rm -f " + szInputFilename + " " + szH264Filename + " " + szOutputFilename).c_str());
282#endif
283
285 // Decode the depth measure.
287 // Create a cv::Mat to store the decoded depth measure.
288 cv::Mat cvDecodedDepth(cvEncodedDepth.rows, cvEncodedDepth.cols, CV_16UC1, cv::Scalar(0));
289 // Decode each pixel in the encoded depth image.
290 for (int nY = 0; nY < cvEncodedDepth.rows; ++nY)
291 {
292 for (int nX = 0; nX < cvEncodedDepth.cols; ++nX)
293 {
294 // Extract the encoded depth values.
295 cv::Vec3b cvPixel = cvEncodedDepth.at<cv::Vec3b>(nY, nX);
296
297 // Extract encoded values.
298 float fL = cvPixel[0] / 255.0f;
299 float fHa = cvPixel[1] / 255.0f;
300 float fHb = cvPixel[2] / 255.0f;
301
302 // Period for triangle waves.
303 float fP = fNP / fW;
304
305 // Determine offset and fine-grain correction.
306 int fM = static_cast<int>(std::floor((4.0f * (fL / fP)) - 0.5f)) % 4;
307 float fL0 = fL - fmod(fL - (fP / 8.0f), fP) + ((fP / 4.0f) * fM) - (fP / 8.0f);
308
309 float fDelta = 0.0f;
310 if (fM == 0)
311 fDelta = (fP / 2.0f) * fHa;
312 else if (fM == 1)
313 fDelta = (fP / 2.0f) * fHb;
314 else if (fM == 2)
315 fDelta = (fP / 2.0f) * (1.0f - fHa);
316 else if (fM == 3)
317 fDelta = (fP / 2.0f) * (1.0f - fHb);
318
319 // Combine to compute the original depth.
320 float fDepth = fW * (fL0 + fDelta);
321
322 // Clamp the depth value to valid range.
323 if (fDepth < 0.0f)
324 fDepth = 0.0f;
325 else if (fDepth > fW)
326 fDepth = fW;
327
328 // Store the decoded depth.
329 cvDecodedDepth.at<uint16_t>(nY, nX) = static_cast<uint16_t>(fDepth);
330 }
331 }
332
333 // Display the original and decoded depth measures.
334 cv::imshow("Original Depth Measure", cvDepthMeasure);
335 cv::imshow("Decoded Depth Measure", cvDecodedDepth);
336 // Set mouse callbacks for original and decoded depth images.
337 cv::setMouseCallback("Original Depth Measure", OriginalDepthMouseCallback, &cvDepthMeasure);
338 cv::setMouseCallback("Decoded Depth Measure", DecodedDepthMouseCallback, &cvDecodedDepth);
339 // Print instructions for the user.
340 std::cout << "Click on images to see depth values. Press 'q' or ESC to exit." << std::endl;
341
342 // Wait for 'q' or ESC key to be pressed.
343 int nKey;
344 while (true)
345 {
346 nKey = cv::waitKey(0); // Wait indefinitely for a key press.
347 if (nKey == 'q' || nKey == 27) // 'q' or ESC.
348 break;
349 }
351
352 // Use the decoded depth measure to calculate a point cloud.
353 cv::Mat cvPointCloud(cvDecodedDepth.rows, cvDecodedDepth.cols, CV_32FC4, cv::Scalar(0));
354 // Camera parameters.
355 double dHorizontalFOV = 90.0; // Horizontal field of view in degrees.
356 double dVerticalFOV = 60.0; // Vertical field of view in degrees.
357 // Calculate focal lengths from FOV.
358 const double dRadPerDeg = M_PI / 180.0;
359 const double dFx = (cvDecodedDepth.cols / 2.0) / tan(dHorizontalFOV * dRadPerDeg / 2.0);
360 const double dFy = (cvDecodedDepth.rows / 2.0) / tan(dVerticalFOV * dRadPerDeg / 2.0);
361
362 // Image center. (principal point)
363 const double dCx = cvDecodedDepth.cols / 2.0;
364 const double dCy = cvDecodedDepth.rows / 2.0;
365
366 // Calculate 3D points from depth values.
367 for (int nY = 0; nY < cvDecodedDepth.rows; ++nY)
368 {
369 for (int nX = 0; nX < cvDecodedDepth.cols; ++nX)
370 {
371 // Get depth value.
372 float fDepth = static_cast<float>(cvDecodedDepth.at<uint16_t>(nY, nX));
373
374 // Skip invalid depth values.
375 if (fDepth <= 0)
376 {
377 cvPointCloud.at<cv::Vec4f>(nY, nX) = cv::Vec4f(0, 0, 0, 0);
378 continue;
379 }
380
381 // Convert from pixel coordinates to 3D coordinates.
382 float fX = static_cast<float>((nX - dCx) * fDepth / dFx);
383 float fY = static_cast<float>((nY - dCy) * fDepth / dFy);
384 float fZ = fDepth;
385
386 // Store point. (XYZ + intensity, using Y channel for intensity)
387 cvPointCloud.at<cv::Vec4f>(nY, nX) = cv::Vec4f(fX, fY, fZ, 255);
388 }
389 }
390 std::cout << "Point cloud generated with " << (cvDecodedDepth.rows * cvDecodedDepth.cols) << " points." << std::endl;
391
392 // Use PCL to visualize the point cloud.
393 pcl::PointCloud<pcl::PointXYZ>::Ptr pclCloud(new pcl::PointCloud<pcl::PointXYZ>());
394 // Convert the OpenCV point cloud to PCL format.
395 pclCloud->width = cvPointCloud.cols;
396 pclCloud->height = cvPointCloud.rows;
397 pclCloud->is_dense = false;
398 pclCloud->points.resize(pclCloud->width * pclCloud->height);
399
400 // Copy points from OpenCV format to PCL format.
401 for (int nY = 0; nY < cvPointCloud.rows; ++nY)
402 {
403 for (int nX = 0; nX < cvPointCloud.cols; ++nX)
404 {
405 cv::Vec4f point = cvPointCloud.at<cv::Vec4f>(nY, nX);
406 size_t idx = nY * cvPointCloud.cols + nX;
407
408 // Only add points with valid depth.
409 if (point[2] > 0)
410 {
411 pclCloud->points[idx].x = point[0];
412 pclCloud->points[idx].y = point[1];
413 pclCloud->points[idx].z = point[2];
414 }
415 else
416 {
417 // For invalid points, set to NaN.
418 pclCloud->points[idx].x = std::numeric_limits<float>::quiet_NaN();
419 pclCloud->points[idx].y = std::numeric_limits<float>::quiet_NaN();
420 pclCloud->points[idx].z = std::numeric_limits<float>::quiet_NaN();
421 }
422 }
423 }
424
425 // Remove NaN points to clean up the cloud..
426 pcl::PointCloud<pcl::PointXYZ>::Ptr pclFilteredPointCloud(new pcl::PointCloud<pcl::PointXYZ>);
427 std::vector<int> vIndices;
428 pcl::removeNaNFromPointCloud(*pclCloud, *pclFilteredPointCloud, vIndices);
429 std::cout << "Point cloud filtered: " << pclFilteredPointCloud->points.size() << " valid points." << std::endl;
430
431 // Downsample the point cloud for better visualization performance.
432 pcl::PointCloud<pcl::PointXYZ>::Ptr pclDownsampledPointCloud(new pcl::PointCloud<pcl::PointXYZ>);
433 pcl::VoxelGrid<pcl::PointXYZ> pclVoxelGrid;
434 pclVoxelGrid.setInputCloud(pclFilteredPointCloud);
435 pclVoxelGrid.setLeafSize(5.0f, 5.0f, 5.0f);
436 pclVoxelGrid.filter(*pclDownsampledPointCloud);
437 std::cout << "Point cloud downsampled to " << pclDownsampledPointCloud->points.size() << " points." << std::endl;
438
439 // Create a PCL visualizer.
440 pcl::visualization::PCLVisualizer::Ptr pclViewer(new pcl::visualization::PCLVisualizer("Depth Point Cloud"));
441 pclViewer->setBackgroundColor(0, 0, 0);
442 pclViewer->addPointCloud<pcl::PointXYZ>(pclDownsampledPointCloud, "depth_cloud");
443 pclViewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, "depth_cloud");
444 pclViewer->addCoordinateSystem(1000.0);
445 pclViewer->initCameraParameters();
446
447 std::cout << "Visualizing point cloud. Close the pclViewer window to continue." << std::endl;
448
449 // Wait for the pclViewer to close.
450 while (!pclViewer->wasStopped())
451 {
452 pclViewer->spinOnce(100);
453 }
454}
void DecodedDepthMouseCallback(int nEvent, int nX, int nY, int nFlags, void *pUserData)
This is a mouse callback function that will be called when the user clicks on the decoded depth image...
Definition DepthMeasureEncodeDecode.hpp:72
void OriginalDepthMouseCallback(int nEvent, int nX, int nY, int nFlags, void *pUserData)
This is a mouse callback function that will be called when the user clicks on the original depth imag...
Definition DepthMeasureEncodeDecode.hpp:44
CV_NODISCARD_STD Mat clone() const
bool empty() const
Point2i Point
Vec< float, 4 > Vec4f
Scalar_< double > Scalar
Vec< uchar, 3 > Vec3b
#define CV_32FC4
#define CV_16UC1
unsigned char uchar
#define CV_8UC3
__device__ __forceinline__ float3 tan(const uchar3 &a)
void imshow(const String &winname, InputArray mat)
int waitKey(int delay=0)
void destroyAllWindows()
void setMouseCallback(const String &winname, MouseCallback onMouse, void *userdata=0)
Mat imread(const String &filename, int flags=IMREAD_COLOR)
bool imwrite(const String &filename, InputArray img, const std::vector< int > &params=std::vector< int >())
void fillConvexPoly(InputOutputArray img, InputArray points, const Scalar &color, int lineType=LINE_8, int shift=0)
Here is the call graph for this function: