我希望调整灰度图像的大小并发布它,以便我可以在另一个ROS节点中使用它。但是我遇到了频道信息的问题,即OpenCV或CvBridge。
当连接相机(网络摄像头/ kinect)并将其转换为' mono8' (灰色)你得到以下信息(行,列,通道),其中的通道= 1.出于某种原因,如果你保存这个图像并再次读取它突然channel = 3.为什么这很重要?如果在具有3个通道的图像上使用cv2.resize(image,x,y),则输出图像为(x,y,channels = 3),但是当只有1个通道时,此信息将丢失且输出为( X,Y)。这个问题是CvBridge在没有频道信息的情况下无法工作。
以下代码有效,因为cv2.resize在3个通道上执行:
#!/usr/bin/env python
PKG = 'something'
import roslib; roslib.load_manifest(PKG)
import rospy
import cv2
import sys
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
class Test:
def __init__(self):
self.image_sub = rospy.Subscriber("/camera/rgb/image_raw",Image, self.callback)
self.image_sub = rospy.Subscriber("test_image",Image, self.callback2)
self.image_pub = rospy.Publisher("test_image", Image)
self.bridge = CvBridge()
def callback(self, image):
try:
cv_image = self.bridge.imgmsg_to_cv2(image, 'mono8')
except CvBridgeError, e:
print e
print cv_image.shape ### output: (480, 640, 1)
cv2.imshow("Test", cv_image)
cv2.imwrite("Test.png", cv_image)
cv2.waitKey(3)
test2 = cv2.imread("Test.png")
print test2.shape ### output: (480, 640, 3)
cv2.imshow("Test 2",test2)
cv2.waitKey(3)
test2 = cv2.resize(test2,(250,240))
print test2.shape ### output: (250, 240, 3)
self.image_pub.publish(self.bridge.cv2_to_imgmsg(test2))
def callback2(self, image):
try:
cv_image = self.bridge.imgmsg_to_cv2(image)
except CvBridgeError, e:
print e
cv2.imshow("Test3", cv_image)
cv2.waitKey(3)
def main(args):
test = Test()
rospy.init_node('image_converter', anonymous=True)
try:
rospy.spin()
except KeyboardInterrupt:
print "Shutting down"
cv2.destroyAllWindows()
if __name__ == '__main__':
main(sys.argv)
但以下情况不起作用(这次尝试发布调整大小):
print cv_image.shape ### output: (480, 640, 1)
cv2.imshow("Test", cv_image)
cv2.imwrite("Test.png", cv_image)
cv2.waitKey(3)
test2 = cv2.resize(test2,(250,240))
print test2.shape ### output: (250, 240)
self.image_pub.publish(self.bridge.cv2_to_imgmsg(test2)) ### ERROR
test2 = cv2.imread("Test.png")
print test2.shape
cv2.imshow("Test 2",test2)
cv2.waitKey(3)
更改' mono8'到' 8UC3'给出以下错误:[yuv422]是一种颜色格式,但[8UC3]不是这样,它们必须具有相同的OpenCV类型,CV_8UC3,CV16UC1
如何调整灰度图像并将其发布到ROS中,而不会丢失频道信息或以某种方式将其转换为3个频道?我唯一担心的是我可以发送调整后的信息,频道数对我来说并不重要。
Ubuntu 12.04, ROS Hydro, OpenCV 2.4.9
答案 0 :(得分:0)
在CvBridge的主分支中,它现在已经修复,您可以发送没有频道信息的图像:https://github.com/ros-perception/vision_opencv/issues/49。
对于不在主分支机构的人:
#Ugly gray 3 channel hack for CvBridge (old version)
#Save image
cv2.imwrite(self.dir_image_save+'tempface.png', cv2_image)
#Load
cv2_image = cv2.imread(self.dir_image_save+'tempface.png')
现在你有一个3通道的灰色图像(但很难看)。