3、添加摄像头后,ROS opencv订阅图像
@ Desmond | Friday, Apr 14, 2023 | 1 minute read | Update at Friday, Apr 14, 2023

ros图像话题和opencv图像转换:Converting between ROS images and OpenCV images (Python)

上一步在仿真环境里添加了摄像头之后,现在需要订阅/iris/usb_cam/image_raw 并且需要用opencv进行处理:

#!/usr/bin/env python
#!/usr/bin/python#-*- coding: utf-8 -*-
import rospy
from mavros_msgs.msg import GlobalPositionTarget, State
from mavros_msgs.srv import CommandBool, CommandTOL, SetMode
from geometry_msgs.msg import PoseStamped, Twist
from sensor_msgs.msg import Imu, NavSatFix, Image
from std_msgs.msg import Float32, String
from pyquaternion import Quaternion
import time
import math
import numpy as np
import cv2
from cv_bridge import CvBridge


class cameraRead:
def __init__(self):
    self.cv_image = None
    self.get_image_sub = rospy.Subscriber("/iris/usb_cam/image_raw", Image, callback = self.get_image_callback) # 接收gazebo无人机图像


def start(self):
    rospy.init_node("camera_node")
    rate = rospy.Rate(20)

    while(not rospy.is_shutdown()):
        self.process_img()
        rate.sleep()


def process_img(self):
    if(self.cv_image is not None):
    cv2.imshow('image', self.cv_image)
    cv2.waitKey(1)



def get_image_callback(self, image_msg):
    bridge = CvBridge()
    self.cv_image = bridge.imgmsg_to_cv2(image_msg, desired_encoding='bgr8')# 转化为opencv图像


if __name__ == "__main__":
    camera = cameraRead()
    camera.start()
ros
Save as image

Social Links