我有一系列来自视频流的图像,我想用 Matplotlib 显示(灰度)。出于某种原因,我可以让它们以完美的颜色显示,但当我将它们转换为灰度时就不行了。
由于我有很多图像,所以我使用它来set_data( image )
代替,imshow( image )
因为它要快得多。彩色图像适用于这两个命令,但灰度仅适用于imshow()
. 如果我使用set_data()
,我只会得到一个黑色图像,无论我发送什么数据。
知道这里会发生什么吗?
我的代码如下供参考。我用一个大注释突出了重要的一点,但我已经包含了我所有的其他代码,以防其他原因导致问题。其余代码基本上设置了一个队列,其中填充了来自相机的图像,我想在获得它们时显示它们。
import matplotlib.pyplot as plt
from matplotlib import cm
from cv_bridge import CvBridge, CvBridgeError
import cv
from collections import deque
import rospy
from sensor_msgs.msg import Image
import numpy as np
class CameraViewer():
def __init__( self, root='navbot' ):
self.root = root
self.im_data = deque()
self.bridge = CvBridge() # For converting ROS images into a readable format
self.im_fig = plt.figure( 1 )
self.im_ax = self.im_fig.add_subplot(111)
self.im_ax.set_title("DVS Image")
self.im_im = self.im_ax.imshow( np.zeros( ( 256, 256 ),dtype='uint8' ), cmap=plt.cm.gray ) # Blank starting image
#self.im_im = self.im_ax.imshow( np.zeros( ( 256, 256 ),dtype='float32' ), cmap=plt.cm.gray ) # Tried a different format, also didn't work
self.im_fig.show()
self.im_im.axes.figure.canvas.draw()
def im_callback( self, data ):
cv_im = self.bridge.imgmsg_to_cv( data, "mono8" ) # Convert Image from ROS Message to greyscale CV Image
im = np.asarray( cv_im ) # Convert from CV image to numpy array
#im = np.asarray( cv_im, dtype='float32' ) / 256 # Tried a different format, also didn't work
self.im_data.append( im )
def run( self ):
rospy.init_node('camera_viewer', anonymous=True)
sub_im = rospy.Subscriber( self.root + '/camera/image', Image, self.im_callback)
while not rospy.is_shutdown():
if self.im_data:
im = self.im_data.popleft()
#######################################################
# The following code is supposed to display the image:
#######################################################
self.im_im.set_cmap( 'gray' ) # This doesn't seem to do anything
self.im_im.set_data( im ) # This won't show greyscale images
#self.im_ax.imshow( im, cmap=plt.cm.gray ) # If I use this, the code runs unbearably slow
self.im_im.axes.figure.canvas.draw()
def main():
viewer = CameraViewer( root='navbot' )
viewer.run()
if __name__ == '__main__':
main()