我想要的是
我希望调整一个灰色图像的大小并发布它,以便可以在另一个ROS节点中使用它。但是,我遇到了 channel 信息的问题,它是OpenCV或CvBridge。
错误
侦听摄像头(网络摄像头/ kinect)并将其转换为“mono8”(灰色)时,您会获得以下信息(行,列,通道),其中channel =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个通道?我唯一关心的是我可以发送调整后的信息, channel 的数量对我来说并不重要。
信息
Ubuntu 12.04,
ROS Hydro,
OpenCV 2.4.9
最佳答案
在CvBridge的主分支中,现在已修复,您可以发送不带 channel 信息的图像:https://github.com/ros-perception/vision_opencv/issues/49。
对于不在master分支上的人:
#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通道的灰色图像(但是很丑)。