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

相关推荐
weixin_443290691 分钟前
【阅读记录-章节7】Build a Large Language Model (From Scratch)
人工智能·语言模型·自然语言处理
橙狮科技2 分钟前
提示词工程教程(零):提示词工程教程简介
人工智能·搜索引擎·语言模型
chengxuyuan1213_6 分钟前
python常用基础语法
开发语言·windows·python
engchina33 分钟前
CUTLASS:高性能 CUDA 线性代数模板库详解
人工智能·线性代数·cuda·cutlass
arong_xu44 分钟前
Modern C++ std::atomic简介
开发语言·c++·atomic
带我去滑雪1 小时前
基于三种机器学习方法的磁芯损耗预测模型
人工智能·机器学习
猫头不能躺1 小时前
【pytorch】卷积神经网络
人工智能·pytorch·cnn
无水先生1 小时前
集成技术综合指南:Bagging 和 Boosting
人工智能·算法·机器学习
chusheng18401 小时前
Python+Django 技术实现自动化漏洞扫描系统开发
python·django·自动化·漏洞扫描·漏洞扫描系统
浮生如梦_1 小时前
C#Halcon图像处理畸变校正之曲面校正
图像处理·人工智能·算法·c#·视觉检测