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
ZEDSLAM.hpp
1
11
18
19// Standard includes
20#include <chrono>
21#include <future>
22
23// Include OpenCV headers.
24#include <opencv2/core/cuda.hpp>
25#include <opencv2/opencv.hpp>
26
27// Include PCL headers.
28#include <pcl/common/transforms.h>
29#include <pcl/filters/voxel_grid.h>
30#include <pcl/impl/point_types.hpp>
31#include <pcl/pcl_macros.h>
32#include <pcl/point_cloud.h>
33#include <pcl/point_types.h>
34#include <pcl/registration/icp.h>
35#include <pcl/visualization/pcl_visualizer.h>
36
37// Declare file constants.
38const bool ENABLE_SPATIAL_MAPPING = false;
39
40
49pcl::PointCloud<pcl::PointXYZ>::Ptr convertCVMatToPCL(const cv::Mat& cvPointCloud)
50{
51 pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
52 // Loop over all pixels
53 for (int i = 0; i < cvPointCloud.rows; ++i)
54 {
55 for (int j = 0; j < cvPointCloud.cols; ++j)
56 {
57 // Access the 4-channel float vector.
58 cv::Vec4f point = cvPointCloud.at<cv::Vec4f>(i, j);
59 // Check for valid (finite) points.
60 if (std::isfinite(point[0]) && std::isfinite(point[1]) && std::isfinite(point[2]))
61 {
62 pcl::PointXYZ pclPoint;
63 pclPoint.x = point[0];
64 pclPoint.y = point[1];
65 pclPoint.z = point[2];
66 cloud->points.push_back(pclPoint);
67 }
68 }
69 }
70 cloud->width = static_cast<uint32_t>(cloud->points.size());
71 cloud->height = 1;
72 return cloud;
73}
74
75
82void RunExample()
83{
84 // Initialize and start handlers.
85 globals::g_pCameraHandler = new CameraHandler();
86
87 // Get pointer to camera.
88 std::shared_ptr<ZEDCamera> pExampleZEDCam1 = globals::g_pCameraHandler->GetZED(CameraHandler::ZEDCamName::eHeadMainCam);
89 // Start ZED cam.
90 pExampleZEDCam1->Start();
91
92 // Turn on ZED features.
93 pExampleZEDCam1->EnablePositionalTracking();
94 // Check if we should turn on spatial mapping.
95 if (ENABLE_SPATIAL_MAPPING)
96 {
97 // Enable spatial mapping.
98 pExampleZEDCam1->EnableSpatialMapping();
99 }
100
101 // Declare mats to store images in.
102 cv::Mat cvNormalFrame1;
103 cv::Mat cvDepthFrame1;
104 cv::Mat cvPointCloud1;
105 cv::Mat cvPointCloudColor1;
106 cv::cuda::GpuMat cvGPUNormalFrame1;
107 cv::cuda::GpuMat cvGPUDepthFrame1;
108 cv::cuda::GpuMat cvGPUPointCloud1;
109 // Declare other data types to store data in.
110 ZEDCam::Pose stPose;
111
112 // Declare FPS counter.
113 IPS FPS = IPS();
114
115 // ----- SLAM Setup -----
116 // Global map for accumulated point clouds.
117 pcl::PointCloud<pcl::PointXYZ>::Ptr pclGlobalMap(new pcl::PointCloud<pcl::PointXYZ>);
118 // Create a PCL visualizer.
119 pcl::visualization::PCLVisualizer::Ptr pclViewer(new pcl::visualization::PCLVisualizer("SLAM Viewer"));
120 // pclViewer->setBackgroundColor(0, 0, 0);
121 // // For timing the SLAM update (once per second)
122 // auto last_slam_time = std::chrono::steady_clock::now();
123
124 // Loop forever, or until user hits ESC.
125 while (true)
126 {
127 // Create instance variables.
128 std::future<bool> fuFrameCopyStatus;
129 std::future<bool> fuDepthCopyStatus;
130 std::future<bool> fuPointCloudCopyStatus;
131
132 // Check if the camera is setup to use CPU or GPU mats.
133 if (pExampleZEDCam1->GetUsingGPUMem())
134 {
135 // Grab frames from camera.
136 fuFrameCopyStatus = pExampleZEDCam1->RequestFrameCopy(cvGPUNormalFrame1);
137 fuDepthCopyStatus = pExampleZEDCam1->RequestDepthCopy(cvGPUDepthFrame1, false);
138 fuPointCloudCopyStatus = pExampleZEDCam1->RequestPointCloudCopy(cvGPUPointCloud1);
139 }
140 else
141 {
142 // Grab frames from camera.
143 fuFrameCopyStatus = pExampleZEDCam1->RequestFrameCopy(cvNormalFrame1);
144 fuDepthCopyStatus = pExampleZEDCam1->RequestDepthCopy(cvDepthFrame1, false);
145 fuPointCloudCopyStatus = pExampleZEDCam1->RequestPointCloudCopy(cvPointCloud1);
146 }
147 // Grab other info from camera.
148 std::future<bool> fuPoseCopyStatus = pExampleZEDCam1->RequestPositionalPoseCopy(stPose);
149
150 // Wait for the frames to be copied.
151 if (fuFrameCopyStatus.get() && fuDepthCopyStatus.get() && fuPointCloudCopyStatus.get())
152 {
153 // Check if the camera is setup to use CPU or GPU mats.
154 if (pExampleZEDCam1->GetUsingGPUMem())
155 {
156 // Download memory from GPU mats if necessary.
157 cvGPUNormalFrame1.download(cvNormalFrame1);
158 cvGPUDepthFrame1.download(cvDepthFrame1);
159 cvGPUPointCloud1.download(cvPointCloud1);
160 }
161
162 // Put FPS on normal frame.
163 cv::putText(cvNormalFrame1,
164 std::to_string(pExampleZEDCam1->GetIPS().GetExactIPS()),
165 cv::Point(50, 50),
167 1,
168 cv::Scalar(255, 255, 255));
169
170 // Put FPS on depth frame.
171 cv::putText(cvDepthFrame1,
172 std::to_string(pExampleZEDCam1->GetIPS().GetExactIPS()),
173 cv::Point(50, 50),
175 1,
176 cv::Scalar(255, 255, 255));
177
178 // Split color from point cloud.
179 imgops::SplitPointCloudColors(cvPointCloud1, cvPointCloudColor1);
180
181 // Wait for the other info to be copied.
182 if (fuPoseCopyStatus.get())
183 {
184 LOG_INFO(logging::g_qConsoleLogger,
185 "Positional Tracking: X: {} | Y: {} | Z: {}",
186 stPose.stTranslation.dX,
187 stPose.stTranslation.dY,
188 stPose.stTranslation.dZ);
189 LOG_INFO(logging::g_qConsoleLogger,
190 "Positional Orientation: Roll: {} | Pitch: {} | Yaw: {}",
191 stPose.stEulerAngles.dXO,
192 stPose.stEulerAngles.dYO,
193 stPose.stEulerAngles.dZO);
194 }
195
196 // Print info.
197 LOG_INFO(logging::g_qConsoleLogger, "ZED Getter FPS: {} | 1% Low: {}", pExampleZEDCam1->GetIPS().GetAverageIPS(), pExampleZEDCam1->GetIPS().Get1PercentLow());
198 // Check if spatial mapping is enabled.
199 if (ENABLE_SPATIAL_MAPPING)
200 {
201 LOG_INFO(logging::g_qConsoleLogger, "Spatial Mapping State: {}", sl::toString(pExampleZEDCam1->GetSpatialMappingState()).get());
202 }
203
204 // Display frames.
205 cv::imshow("FRAME1", cvNormalFrame1);
206 cv::imshow("DEPTH1", cvDepthFrame1);
207 cv::imshow("POINT CLOUD COLOR 1", cvPointCloudColor1);
208
209 // ----- SLAM Processing: once per second -----
210 // auto now = std::chrono::steady_clock::now();
211 // if (std::chrono::duration_cast<std::chrono::seconds>(now - last_slam_time).count() >= 1)
212 // {
213 // last_slam_time = now;
214 // // Convert the acquired cv::Mat point cloud to a PCL point cloud.
215 // pcl::PointCloud<pcl::PointXYZ>::Ptr current_cloud = convertCVMatToPCL(cvPointCloud1);
216
217 // // Optional: Downsample the current scan with a VoxelGrid filter.
218 // pcl::VoxelGrid<pcl::PointXYZ> voxel;
219 // voxel.setInputCloud(current_cloud);
220 // voxel.setLeafSize(0.05f, 0.05f, 0.05f); // Adjust leaf size as needed.
221 // pcl::PointCloud<pcl::PointXYZ>::Ptr filtered_cloud(new pcl::PointCloud<pcl::PointXYZ>);
222 // voxel.filter(*filtered_cloud);
223
224 // // If the global map is empty, initialize it with the current scan.
225 // if (pclGlobalMap->points.empty())
226 // {
227 // *pclGlobalMap = *filtered_cloud;
228 // }
229 // else
230 // {
231 // // Register the current scan to the global map using ICP.
232 // pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp;
233 // icp.setInputSource(filtered_cloud);
234 // icp.setInputTarget(pclGlobalMap);
235 // pcl::PointCloud<pcl::PointXYZ> aligned;
236 // icp.align(aligned);
237
238 // if (icp.hasConverged())
239 // {
240 // // Get the transformation from ICP.
241 // Eigen::Matrix4f icp_transform = icp.getFinalTransformation();
242 // // Transform the current scan into the global coordinate frame.
243 // pcl::PointCloud<pcl::PointXYZ>::Ptr transformed_cloud(new pcl::PointCloud<pcl::PointXYZ>);
244 // pcl::transformPointCloud(*filtered_cloud, *transformed_cloud, icp_transform);
245 // // Fuse the transformed scan into the global map.
246 // *pclGlobalMap += *transformed_cloud;
247 // }
248 // else
249 // {
250 // LOG_WARNING(logging::g_qConsoleLogger, "ICP did not converge for the current scan.");
251 // }
252 // }
253
254 // // Update the PCL visualizer.
255 // pclViewer->removeAllPointClouds();
256 // pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> color_handler(pclGlobalMap, 255, 255, 255);
257 // pclViewer->addPointCloud<pcl::PointXYZ>(pclGlobalMap, color_handler, "pclGlobalMap");
258 // pclViewer->spinOnce(10);
259 // }
260 }
261
262 // Tick FPS counter.
263 FPS.Tick();
264 // Print FPS of main loop.
265 LOG_INFO(logging::g_qConsoleLogger, "Main FPS: {}", FPS.GetAverageIPS());
266
267 char chKey = cv::waitKey(1);
268 if (chKey == 27) // Press 'Esc' key to exit
269 break;
270 }
271
272 // Close all OpenCV windows.
274
275 // Check if spatial mapping is enabled.
276 if (ENABLE_SPATIAL_MAPPING)
277 {
278 // Extract spatial map.
279 std::future<sl::Mesh> fuSpatialMap;
280 pExampleZEDCam1->ExtractSpatialMapAsync(fuSpatialMap);
281 sl::Mesh slSpatialMap = fuSpatialMap.get();
282 slSpatialMap.save("test.obj", sl::MESH_FILE_FORMAT::PLY);
283 }
284
286 // Cleanup.
288 // Stop RoveComm quill logging or quill will segfault if trying to output logs to RoveComm.
289 network::g_bRoveCommUDPStatus = false;
290 network::g_bRoveCommTCPStatus = false;
291
292 // Stop camera threads.
293 globals::g_pCameraHandler->StopAllCameras();
294}
Declares constants for the autonomy software.
Defines functions and objects used project wide.
Implements Logging for Autonomy.
Defines functions and objects used for Autonomy Networking.
This file is a utility used to check if any file from the example directory has been included....
void RunExample()
Example function to demonstrate the usage of LiDARHandler.
Definition GeoPlanner.hpp:25
Defines and implements functions related to GENERAL operations on images. All functions are defined w...
The CameraHandler class is responsible for managing all of the camera feeds that Autonomy_Software us...
Definition CameraHandler.h:34
This util class provides an easy way to keep track of iterations per second for any body of code.
Definition IPS.hpp:30
double GetAverageIPS() const
Calculates the average iterations per second.
Definition IPS.hpp:180
void Tick()
This method is used to update the iterations per second counter and recalculate all of the IPS metric...
Definition IPS.hpp:138
_Tp & at(int i0=0)
void download(OutputArray dst) const
Point2i Point
Vec< float, 4 > Vec4f
Scalar_< double > Scalar
void imshow(const String &winname, InputArray mat)
int waitKey(int delay=0)
void destroyAllWindows()
void putText(InputOutputArray img, const String &text, Point org, int fontFace, double fontScale, Scalar color, int thickness=1, int lineType=LINE_8, bool bottomLeftOrigin=false)
FONT_HERSHEY_COMPLEX
::uint32_t uint32_t
void SplitPointCloudColors(cv::Mat &cvInputPointCloud, cv::Mat &cvOutputColors)
Given a cv::Mat containing X, Y, Z, and BGRA values for each pixel in the third dimension,...
Definition ImageOperations.hpp:181
This struct is used within the ZEDCam class to store the camera pose with high precision....
Definition ZEDCamera.hpp:77