通过python (ROS Kinetic)中的OpenCV访问图像



我想在ros动力学中使用OpenCV访问我的相机,这是我的代码

#!/usr/bin/env python2.7
import rospy
from sensor_msgs.msg import Image
import cv2
from cv_bridge import CvBridge, CvBridgeError
rospy.init_node('opencv_example', anonymous=True)
bridge = CvBridge()
def show_image(img):
cv2.imshow("Image Window", img)
cv2.waitKey(3)

def image_callback(img_msg):
try:
cv_image = bridge.imgmsg_to_cv2(img_msg, "passthrough")
except CvBridgeError, e:
rospy.logerr("CvBridge Error: {0}".format(e))

show_image(cv_image)

sub_image = rospy.Subscriber("/raspicam_node/image/compressed", Image, image_callback)
cv2.namedWindow("Image Window", 1)
while not rospy.is_shutdown():
rospy.spin()

在这段代码之后我得到的是一个空白的图像窗口

在你问主题地址之前,我可以用这个命令rostrum image_view image_view image:=/raspicam_node/image/ _image_transport:=compressed访问相机

目前,我正在使用

Ubuntu 16.04
  • Ros动能
  • Open CV 3.3.1

你已经回答了你自己的问题,图像是压缩的。因为你的订阅者也错了,压缩图像有一个特定的sensor_msgs类型。

使用numpy,您可以直接在您的订阅者解码图像,如下所示:

def image_callback(img_msg):
np_arr = np.fromstring(img_msg.data, np.uint8)
image_np = cv2.imdecode(np_arr, cv2.CV_LOAD_IMAGE_COLOR)

show_image(cv_image)

如前所述,您的订阅者还需要看起来像

sub_image = rospy.Subscriber("/raspicam_node/image/compressed", CompressedImage, image_callback)

你需要包括from sensor_msgs.msg import CompressedImage

编辑:

根据您的评论,您也可以将压缩图像作为未压缩图像重新发布,以使用image_transport与原始代码一起使用。

如果您想在终端使用rosrun:rosrun image_transport republish compressed in:=/raspicam_node/image/compressed raw out:=/raspicam_node/image/uncompressed

或者如果你使用启动文件:

<node name="republish" type="republish" pkg="image_transport" output="screen" args="compressed in:=/raspicam_node/image/compressed raw out:=/raspicam_node/image/uncompressed" />

然后你需要把你的原始代码改为

#!/usr/bin/env python2.7
import rospy
from sensor_msgs.msg import Image
import cv2
from cv_bridge import CvBridge, CvBridgeError
rospy.init_node('opencv_example', anonymous=True)
bridge = CvBridge()
def show_image(img):
cv2.imshow("Image Window", img)
cv2.waitKey(3)

def image_callback(img_msg):
try:
cv_image = bridge.imgmsg_to_cv2(img_msg, "passthrough")
except CvBridgeError, e:
rospy.logerr("CvBridge Error: {0}".format(e))

show_image(cv_image)

sub_image = rospy.Subscriber("/raspicam_node/image/uncompressed", Image, image_callback)
cv2.namedWindow("Image Window", 1)
while not rospy.is_shutdown():
rospy.spin()

相关内容

  • 没有找到相关文章

最新更新