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

相关推荐
Coder_Boy_1 分钟前
基于SpringAI的智能AIOps项目:部署相关容器化部署管理技术图解版
人工智能·spring boot·算法·贪心算法·aiops
王哈哈^_^2 分钟前
【完整源码+数据集】道路拥塞数据集,yolo道路拥塞检测数据集 8921 张,交通拥堵识别数据集,路口拥塞识别系统实战教程
深度学习·算法·yolo·目标检测·计算机视觉·分类·毕业设计
大模型铲屎官3 分钟前
【操作系统-Day 47】揭秘Linux文件系统基石:图解索引分配(inode)与多级索引
linux·运维·服务器·人工智能·python·操作系统·计算机组成原理
dagouaofei9 分钟前
2026 年工作计划 PPT 怎么做?多款 AI 生成方案对比分析
人工智能·python·powerpoint
菩提树下的凡夫11 分钟前
如何将python的程序py文件转换为exe程序
开发语言·python
愈努力俞幸运12 分钟前
yaml 入门教程
python
乾元12 分钟前
Network-as-Code:把 HCIE / CCIE 实验脚本转为企业级 CI 工程化流程
运维·网络·人工智能·安全·web安全·ai·架构
skywalk816315 分钟前
Vibe Kanban:一个专门为 ‌AI编程助手(AI coding agents)‌ 设计的开源可视化项目管理工具
人工智能·ai编程
数据分析能量站22 分钟前
2025-个人总结
人工智能
Aaron158828 分钟前
三种主流接收机架构(超外差、零中频、射频直采)对比及发展趋势浅析
c语言·人工智能·算法·fpga开发·架构·硬件架构·信号处理