当前位置:   article > 正文

基于Qt和ros的深度相机的识别测距框架_astra pro 深度相机测距

astra pro 深度相机测距

 效果

实现

本项目采用ros框架,用yolov5作为识别模块,采用奥比中光astra深度相机测距,ui界面显示实时图像,点击显示距离。

代码解释:

思路是把yolov5封装成功能包,用python写一个ros收发接口调用模型。主函数接受yolov5模块识别到的数据,调用深度图像得到距离,再把图像和距离显示在ui界面上。

本程序预留串口通信,可与嵌入式端进行通信,扩展成更多项目。

main.cpp

  1. #include <ros/ros.h>
  2. #include <sensor_msgs/Image.h>
  3. #include <sensor_msgs/image_encodings.h>
  4. #include <cv_bridge/cv_bridge.h>
  5. #include <iostream>
  6. #include <opencv2/opencv.hpp>
  7. #include <opencv2/imgproc/imgproc.hpp>
  8. #include <image_transport/image_transport.h>
  9. #include <sensor_msgs/Image.h>
  10. #include <sensor_msgs/CameraInfo.h>
  11. #include <opencv2/highgui/highgui.hpp>
  12. #include <cv_bridge/cv_bridge.h>
  13. #include <message_filters/subscriber.h>
  14. #include <message_filters/time_synchronizer.h>
  15. #include<message_filters/sync_policies/approximate_time.h>
  16. #include <pcl/point_cloud.h>
  17. #include<thread>
  18. #include<pcl/point_types.h>
  19. #include<pcl_conversions/pcl_conversions.h>
  20. #include<pcl/visualization/cloud_viewer.h>
  21. #include <sensor_msgs/PointCloud2.h>
  22. #include "widget.h"
  23. #include <QApplication>
  24. #include "std_msgs/String.h"
  25. using namespace std;
  26. using namespace sensor_msgs;
  27. using namespace message_filters;
  28. using namespace cv;
  29. typedef pcl::PointXYZRGB PointT;
  30. typedef pcl::PointCloud<PointT> testcloud;
  31. //#include<realsense_dev/depth_value.h> //自定义一个消息类型
  32. cv::Mat depth_pic; //定义全局变量,图像矩阵Mat形式
  33. String some="someee";
  34. char some1[30];
  35. //realsense_dev::depth_value command_to_pub; //待发布数据
  36. double x,y,z;
  37. int n=0;
  38. void depthCallback(const sensor_msgs::Image::ConstPtr&msg)
  39. {
  40. cv_bridge::CvImagePtr Dest ;
  41. Dest = cv_bridge::toCvCopy(msg,sensor_msgs::image_encodings::TYPE_16UC1);
  42. depth_pic = Dest->image;
  43. //cout<<"Output some info about the depth image in cv format"<<endl;
  44. //cout<< "Rows of the depth iamge = "<<depth_pic.rows<<endl; //获取深度图的行数height
  45. //cout<< "Cols of the depth iamge = "<<depth_pic.cols<<endl; //获取深度图的列数width
  46. //cout<< "Type of depth_pic's element = "<<depth_pic.type()<<endl; //深度图的类型
  47. ushort Ld = depth_pic.at<ushort>(command_to_pub2.x+5,command_to_pub2.y+5); //读取深度值,数据类型为ushort单位为mm
  48. ushort Rd = depth_pic.at<ushort>((command_to_pub2.x1+command_to_pub2.x)/2,(command_to_pub2.y1+command_to_pub2.y)/2); //读取深度值,数据类型为ushort单位为mm
  49. //ushort Ld = depth_pic.at<ushort>(400,788); //读取深度值,数据类型为ushort单位为mm
  50. //ushort Rd = depth_pic.at<ushort>(406,800); //读取深度值,数据类型为ushort单位为mm
  51. Rd_value = float(Rd)/1000 ; //强制转换
  52. Ld_value = float(Ld)/1000 ; //强制转换
  53. cout<< "Value of Rdepth_pic's pixel= "<<Rd_value<< "Value of Ldepth_pic's pixel= "<<Ld_value<<endl; //读取深度值
  54. }
  55. void imageCallback(const sensor_msgs::ImageConstPtr& msg)
  56. {
  57. // clock_t start,ends;
  58. // start=clock();
  59. try
  60. {
  61. cv::Mat image = cv_bridge::toCvShare(msg, "bgra8")->image; //image_raw就是我们得到的图像了
  62. int rows = image.rows;//std::cout<<"rows="<<rows<<std::endl;
  63. int cols = image.cols;//std::cout<<"cols="<<cols<<std::endl;
  64. cvimage=image;
  65. }
  66. catch (cv_bridge::Exception &e)
  67. {
  68. ROS_ERROR("Could not conveextrinsicMat_RT from '%s' to 'rgb8'.", msg->encoding.c_str());
  69. }
  70. // ends=clock();
  71. // std::cout<<"img call:"<<(double (ends-start)/CLOCKS_PER_SEC)<<std::endl;
  72. }
  73. void leidaCallback(const std_msgs::String::ConstPtr& msg_p)
  74. {
  75. ROS_INFO("%s",msg_p->data.c_str());
  76. some=msg_p->data.c_str();
  77. //ROS_INFO("我听见:%s",(*msg_p).data.c_str());
  78. char x[6],y[6],x1[6],y1[6];
  79. int i;
  80. for(i=0;i<some.length();i++)
  81. {
  82. if(some[i-1]=='F' && some[i]=='C')
  83. {
  84. command_to_pub1.Value[0]=some[i+1];
  85. command_to_pub1.Value[1]=some[i+2];
  86. }
  87. if(some[i-1]=='y') //x y q w h
  88. {
  89. for(int q=0;q<6;q++)
  90. {
  91. if(some[i+q]!= '.' )
  92. {
  93. y[q]=some[i+q];
  94. if(some[i+q]== 'q' )
  95. {
  96. break;
  97. }
  98. }
  99. else
  100. {
  101. continue;
  102. }
  103. }
  104. }
  105. if(some[i-1]=='x')
  106. {
  107. for(int q=0;q<6;q++)
  108. {
  109. if(some[i+q]!= '.' )
  110. {
  111. x[q]=some[i+q];
  112. if(some[i+q]== 'y' )
  113. {
  114. break;
  115. }
  116. }
  117. else
  118. {
  119. continue;
  120. }
  121. }
  122. }
  123. if(some[i-1]== 'w' )
  124. {
  125. for(int q=0;q<6;q++)
  126. {
  127. if(some[i+q]!= '.' )
  128. {
  129. y1[q]=some[i+q];
  130. if(some[i+q]== 'h' )
  131. {
  132. break;
  133. }
  134. }
  135. else
  136. {
  137. continue;
  138. }
  139. }
  140. }
  141. if( some[i-1]== 'q' )
  142. {
  143. for(int q=0;q<6;q++)
  144. {
  145. if(some[i+q]!= '.' )
  146. {
  147. x1[q]=some[i+q];
  148. if(some[i+q]== 'w' )
  149. {
  150. break;
  151. }
  152. }
  153. else
  154. {
  155. continue;
  156. }
  157. }
  158. }
  159. }
  160. command_to_pub2.x = atoi(x);
  161. command_to_pub2.y= atoi(y);
  162. command_to_pub2.x1= atoi(x1);
  163. command_to_pub2.y1= atoi(y1);
  164. printf("\nsome:%d,%d,%d,%d",command_to_pub2.x,command_to_pub2.y,command_to_pub2.x1,command_to_pub2.y1);
  165. }
  166. int uuu(int argc, char *argv[])
  167. {
  168. QApplication a(argc, argv);
  169. Widget w;
  170. w.show();
  171. return a.exec();
  172. }
  173. void ttt(int argc, char *argv[])
  174. {
  175. ros::init(argc, argv, "stream_pub"); // ros节点初始化
  176. ros::NodeHandle nh; //创建节点句柄
  177. image_transport::ImageTransport it(nh);
  178. ros::AsyncSpinner spinner(1);
  179. spinner.start();
  180. ros::Subscriber sub1 = nh.subscribe<std_msgs::String>("/leida_num",1,leidaCallback);
  181. ros::Subscriber image_sub = nh.subscribe<sensor_msgs::Image>("/camera/depth/image_raw",1,depthCallback); //订阅深度图像
  182. image_transport::Subscriber sub = it.subscribe("/camera/color/image_raw", 1, &imageCallback);
  183. //ros::Subscriber element_sub = nh.subscribe<sensor_msgs::Image>("/camera/aligned_depth_to_color/image_raw",100,pixelCallback); //订阅像素点坐标
  184. //ros::Publisher mode_pub = nh.advertise<realsense_dev::depth_value>("/depth_info", 10);
  185. //command_to_pub.Value = 0; //初始化深度值
  186. ros::Rate rate(20.0); //设定自循环的频率
  187. while(ros::ok)
  188. {
  189. //command_to_pub.header.stamp = ros::Time::now();
  190. //command_to_pub.Value = d_value; //depth_pic.rows/2,depth_pic.cols/2 为像素点
  191. }
  192. ros::Duration(10).sleep(); //设定自循环的频率
  193. }
  194. int main(int argc,char *argv[])
  195. {
  196. int yt;
  197. thread th2(uuu,argc, argv);
  198. thread th3(ttt,argc, argv);
  199. //uuu(argc, argv);
  200. th2.join();
  201. th3.join();
  202. return yt;
  203. }

widget.cpp片段

  1. void Widget::showww()
  2. {
  3. Rect rect(command_to_pub2.x,command_to_pub2.y,
  4. command_to_pub2.x1-command_to_pub2.x,command_to_pub2.y1-command_to_pub2.y);
  5. Mat mat = cvimage;
  6. //cvtColor( mat, mat, COLOR_BGR2RGB);//BGR转化为RGB
  7. QImage::Format format = QImage::Format_ARGB32;
  8. switch ( mat.type())
  9. {
  10. case CV_8UC1:
  11. format = QImage::Format_Indexed8;
  12. break;
  13. case CV_8UC3:
  14. format = QImage::Format_RGB888;
  15. break;
  16. case CV_8UC4:
  17. format = QImage::Format_ARGB32;
  18. break;
  19. }
  20. QImage image = QImage((const uchar*) mat.data, mat.cols, mat.rows,
  21. mat.cols * mat.channels(), format);
  22. /*cvtColor(mat, mat, CV_BGR2RGB);
  23. QImage image(mat.data,
  24. mat.cols,
  25. mat.rows,
  26. mat.step,
  27. QImage::Format_RGB888);*/
  28. //QString filename("/home/q/图片/标定二维码/image/1.bmp");
  29. QImage* img=new QImage;
  30. img=&image;
  31. ui->labImgShow->setPixmap(QPixmap::fromImage(*img));
  32. timer->start(20);//启动计时器
  33. }
  34. void Widget::text()
  35. {
  36. float uio=5.8;
  37. String utf5=to_string( Ld_value);
  38. char utf8[20];
  39. strcpy( utf8,utf5.c_str());
  40. QString str2=QString::fromUtf8(utf8);
  41. ui->Ldepth_textEdit->append(str2); //接收区显示 -- 追加方式
  42. ui->Ldepth_textEdit->show();
  43. String utf6=to_string( Rd_value);
  44. char utf9[20];
  45. strcpy( utf9,utf6.c_str());
  46. QString str3=QString::fromUtf8(utf9);
  47. ui->Rdepth_textEdit->append(str3); //接收区显示 -- 追加方式
  48. ui->Rdepth_textEdit->show();
  49. String utf59= "people";
  50. char utf89[20];
  51. strcpy( utf89,utf59.c_str());
  52. QString str26=QString::fromUtf8(utf89);
  53. ui->name_textEdit->append(str26); //接收区显示 -- 追加方式
  54. ui->name_textEdit->show();
  55. }

yolov5识别片段

  1. # src=cv2.imread('biye.jpg')
  2. def detect(img):
  3. time1 = time.time()
  4. global ros_image
  5. global xytoxy
  6. global label_name
  7. cudnn.benchmark = True
  8. dataset = loadimg(img)
  9. # print(dataset[3])
  10. # plt.imshow(dataset[2][:, :, ::-1])
  11. names = model.module.names if hasattr(model, 'module') else model.names
  12. # colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))]
  13. # colors=[[0,255,0]]
  14. augment = 'store_true'
  15. conf_thres = 0.3
  16. iou_thres = 0.45
  17. classes = (0, 1, 2, 3, 5, 7)
  18. agnostic_nms = 'store_true'
  19. img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img
  20. _ = model(img.half() if half else img) if device.type != 'cpu' else None # run once
  21. path = dataset[0]
  22. img = dataset[1]
  23. im0s = dataset[2]
  24. vid_cap = dataset[3]
  25. img = torch.from_numpy(img).to(device)
  26. img = img.half() if half else img.float() # uint8 to fp16/32
  27. img /= 255.0 # 0 - 255 to 0.0 - 1.0
  28. time2 = time.time()
  29. if img.ndimension() == 3:
  30. img = img.unsqueeze(0)
  31. # Inference
  32. pred = model(img, augment=augment)[0]
  33. # Apply NMS
  34. pred = non_max_suppression(pred, conf_thres, iou_thres, classes=classes, agnostic=agnostic_nms)
  35. view_img = 1
  36. save_txt = 1
  37. save_conf = 'store_true'
  38. time3 = time.time()
  39. for i, det in enumerate(pred): # detections per image
  40. p, s, im0 = path, '', im0s
  41. s += '%gx%g ' % img.shape[2:] # print string
  42. gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
  43. if det is not None:
  44. # print(det)
  45. # Rescale boxes from img_size to im0 size
  46. det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
  47. # Print results
  48. for c in det[:, -1].unique():
  49. n = (det[:, -1] == c).sum() # detections per class
  50. s += '%g %ss, ' % (n, names[int(c)]) # add to string
  51. # Write results
  52. for *xyxy, conf, cls in reversed(det):
  53. if save_txt: # Write to file
  54. xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
  55. line = (cls, conf, *xywh) if save_conf else (cls, *xywh) # label format
  56. y = torch.tensor(xyxy).view(1, 4)
  57. xy = y.clone() if isinstance(y, torch.Tensor) else np.copy(y)
  58. xytoxy = xy.view(-1).tolist()
  59. if view_img: # Add bbox to image
  60. label = '%s %.2f' % (names[int(cls)], conf)
  61. label_name = names[int(cls)]
  62. plot_one_box(xyxy, im0, label=label, color=[0, 255, 0], line_thickness=3)
  63. time4 = time.time()
  64. cv2.putText(im0, str(fps), (20, 20), 0, 0.75, [225, 255, 255], thickness=3, lineType=cv2.LINE_AA)
  65. print('************')
  66. print('2-1', time2 - time1)
  67. print('3-2', time3 - time2)
  68. print('4-3', time4 - time3)
  69. print('total', time4 - time1)
  70. print('xy2xy', xytoxy[0])
  71. print("label_name:", label_name)
  72. some = "FC" + str(label_name) + "x" + str(xytoxy[0]) + "y" + str(xytoxy[1]) + "q" + str(xytoxy[2]) + "w" + str(xytoxy[3]) +"h"+ "RA"
  73. print("label_name:", some)
  74. out_img = im0[:, :, [2, 1, 0]]
  75. ros_image = out_img
  76. cv2.imshow('YOLOV5', out_img)
  77. a = cv2.waitKey(1)
  78. #### Create CompressedIamge ####
  79. # publish_image(im0)
  80. publish_image1(some)

 CmakeList.cpp

  1. cmake_minimum_required(VERSION 3.5)
  2. project(picture2pcl)
  3. ## Compile as C++11, supported in ROS Kinetic and newer
  4. #add_compile_options(-std=c++11)
  5. set(CMAKE_CXX_STANDARD 11)
  6. set(CMAKE_CXX_STANDARD_REQUIRED True)
  7. set(CMAKE_AUTOUIC ON)
  8. set(CMAKE_AUTOMOC ON)
  9. set(CMAKE_AUTORCC ON)
  10. find_library(librealsense REQUIRED)
  11. find_package(catkin REQUIRED COMPONENTS
  12. geometry_msgs
  13. roscpp
  14. rospy
  15. std_msgs
  16. cv_bridge
  17. message_generation
  18. image_transport
  19. pcl_ros
  20. sensor_msgs
  21. tf
  22. )
  23. find_package(Eigen3 REQUIRED)
  24. find_package(PCL REQUIRED)
  25. #find_package(realsense2 REQUIRED)
  26. find_package(OpenCV REQUIRED)
  27. catkin_package(
  28. # INCLUDE_DIRS include
  29. # LIBRARIES realsense_dev
  30. CATKIN_DEPENDS roscpp std_msgs
  31. DEPENDS EIGEN3 PCL OpenCV
  32. INCLUDE_DIRS
  33. # DEPENDS system_lib
  34. )
  35. include_directories(
  36. # include
  37. ${catkin_INCLUDE_DIRS}
  38. ${OpenCV_INCLUDE_DIRS}
  39. ${EIGEN3_INCLUDE_DIR}
  40. ${PCL_INCLUDE_DIRS}
  41. )
  42. #add_executable(stream_pub src/stream_pub.cpp)
  43. #target_link_libraries(stream_pub ${catkin_LIBRARIES} ${OpenCV_LIBS})
  44. #add_executable(main src/main.cpp src/serial_communication.cpp )
  45. #find_package(Qt5 COMPONENTS Widgets REQUIRED)
  46. #find_package(Qt5 COMPONENTS Core SerialPort REQUIRED)
  47. find_package(Qt5Widgets REQUIRED)
  48. find_package(Qt5Core REQUIRED)
  49. find_package(Qt5Gui REQUIRED)
  50. find_package(Qt5SerialPort REQUIRED)
  51. if(ANDROID)
  52. add_library(tongxin11 SHARED
  53. src/main.cpp
  54. src/serial_communication.cpp
  55. src/serial_communication.h
  56. src/main.cpp
  57. src/widget.cpp
  58. src/widget.h
  59. src/widget.ui
  60. )
  61. else()
  62. add_executable(tongxin11
  63. src/main.cpp
  64. src/serial_communication.cpp
  65. src/serial_communication.h
  66. src/main.cpp
  67. src/main.cpp
  68. src/widget.cpp
  69. src/widget.h
  70. src/widget.ui
  71. )
  72. endif()
  73. target_link_libraries(tongxin11 ${Qt5Core_LIBRARIES} ${Qt5Widgets_LIBRARIES} ${Qt5SerialPort_LIBRARIES} ${catkin_LIBRARIES} ${PCL_LIBRARIES} ${OpenCV_LIBS} -lpthread -luuid)
  74. #target_link_libraries(serialportLIB ${Qt5Core_LIBRARIES} ${Qt5Widgets_LIBRARIES} ${Qt5SerialPort_LIBRARIES})
  75. #target_link_libraries(tongxin11 ${catkin_LIBRARIES} ${PCL_LIBRARIES} ${OpenCV_LIBS})

奥比中光深度相机驱动

奥比中光Orbbec Astra深度相机在ROS Melodic的使用_LCH南安的博客-CSDN博客
 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/250761
推荐阅读
相关标签
  

闽ICP备14008679号