其他分享
首页 > 其他分享> > opencv 读取相机图像+ros发布图像

opencv 读取相机图像+ros发布图像

作者:互联网

#!/usr/bin/python2
# coding=utf-8

import cv2
import numpy as np
from std_msgs.msg import Header
from sensor_msgs.msg import Image
import rospy
from cv_bridge import CvBridge , CvBridgeError

capture = cv2.VideoCapture(2)  #使用串口为/dev/video2,注意授权

if __name__=="__main__":
    capture.open(2)  #使用串口为/dev/video2,注意授权
    capture.set(cv2.CAP_PROP_FRAME_WIDTH, 640)    #这里opencv的图像大小与ros发布的图像大小一致
    capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
    capture.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))  
    rospy.init_node('Camera', anonymous=True) #定义节点
    image_pub=rospy.Publisher('/image_view/image_raw',Image,queue_size = 10) #定义话题

    while True:       
            ret, frame = capture.read()
            # cv2.imshow("capture", frame)
            ros_frame = Image()
            header = Header(stamp = rospy.Time.now())
            header.frame_id = "Camera"
            ros_frame.header=header
            ros_frame.width = 640  #尺寸与opencv图像一致
            ros_frame.height = 480
            ros_frame.encoding = "bgr8"
            ros_frame.step = 1920
            ros_frame.data = np.array(frame).tostring() #图片格式转换
            image_pub.publish(ros_frame) #发布消息
            # cv2.waitKey(1)
            rate = rospy.Rate(10) # 10hz 

    capture.release()
    cv2.destroyAllWindows() 




注意点:

1.  新的ros包注意为 .py文件授权为 可执行程序

2.  注意发布的ros图像和opencv读取的图像尺寸相同

3.  注意相机接入的串口是哪个,有没有授权 ,如: chmod  777 /dev/video2

4.  opencv显示图像时,注意加上cv2.waitKey(1)这一句

程序原版来自:ROS操作系统 opencv-python读取摄像头+rviz可视化_吴昊浪的博客-CSDN博客_python rviz

标签:capture,frame,cv2,opencv,图像,import,ros
来源: https://blog.csdn.net/a13956621590/article/details/122117316