OpenCV库及在ROS中使用

OpenCV库及在ROS中使用

依赖

复制代码
cv_bridge image_transport roscpp rospy sensor_msgs std_msgs

CMakeLists.txt添加

cmake 复制代码
find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
target_link_libraries(pub_img_topic ${catkin_LIBRARIES} ${Opencv_LIBS}) 

C++

cpp 复制代码
#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <opencv2/highgui/highgui.hpp>
#include <cv_bridge/cv_bridge.h>

int main(int argc, char** argv)
{
    ros::init(argc, argv, "publisher_img");
    ros::NodeHandle nh;

    image_transport::ImageTransport it(nh);
    image_transport::Publisher pub = it.advertise("image", 1);

    cv::Mat image = cv::imread("/home/ghigher/workplace/pointcloud_ws/src/pub_sub_image/images/ros_logo.png");
    if (image.empty())
    {
        ROS_INFO("Image is Empty!");
    }
    sensor_msgs::ImagePtr msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", image).toImageMsg();
    ros::Rate loop_rate(5);

    while(nh.ok())
    {
        pub.publish(msg);
        ros::spinOnce();
        loop_rate.sleep();
    }
}

python

python 复制代码
#! /usr/bin/env python
#  -*-coding:utf8 -*-

import rospy
import cv2
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Image

class image_converter:
    def __init__(self):
        self.image_pub = rospy.Publisher("cv_bridge_image", Image, queue_size=1)
        self.bridge = CvBridge()
        self.image_sub = rospy.Subscriber("/usb_cam/image_raw", Image, self.callback)
        
    def callback(self, imgmsg):
        cv_image = self.bridge.imgmsg_to_cv2(imgmsg, "bgr8")
        
        cv_image_gray = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY)
        
        cv2.imshow("image", cv_image_gray)
        cv2.waitKey(1)
        
        self.image_pub.publish(self.bridge.cv2_to_imgmsg(cv_image_gray))
        
if __name__ == "__main__":
    try:
        rospy.init_node("cv_to_bridge")
        rospy.loginfo("Starting cv_bridge node ...")
        image_converter()
        rospy.spin()
    except KeyboardInterrupt:
        rospy.loginfo("Shutdown cv_bridge node !!!")
        cv2.destroyAllWindows()

查看rqt_image_view

相关推荐
aneasystone本尊3 分钟前
学习大模型推理的加速技术:量化、投机采样与 PD 分离
人工智能
IT毕设梦工厂15 分钟前
计算机毕业设计选题推荐:基于大数据的房地产交易数据分析与可视化|毕业设计选题|计算机毕设|选题推荐|毕设指导|项目定制|源码|高质量项目
大数据·hive·hadoop·python·数据分析·spark·课程设计
IT_陈寒19 分钟前
Vite热更新失效?你可能漏了这个配置项
前端·人工智能·后端
Wx-bishekaifayuan20 分钟前
springboot生活商城系统21035-计算机课程设计、毕业设计
spring boot·后端·python·spring·elasticsearch·golang·课程设计
EatFan20 分钟前
从 Prompt 到 Harness:AI Agent 的竞争层为什么转移到了“外骨骼“
人工智能·ai agent
知了一笑25 分钟前
企业的AI转型,真能找到出路吗?
人工智能·ai·aigc
UIU11430 分钟前
递归算法与汉诺塔
c++·学习·算法·c#·递归
FYKJ_201031 分钟前
django药饮个性化推荐系统54839-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
whyutianict_vv33 分钟前
从技术栈视角评估AI大模型培训机构:Python、RAG、Agent与部署的能力核对清单
人工智能
天赐范式38 分钟前
天赐范式第175天:让活着的成员互相验证——异质互验与重放反伪造
python·数字生命·天赐范式·动态运行时·互验·重放反伪造