有没有一种方法可以将pyplot.imshow()对象转换为numpy数组? [英] Is there a way to convert pyplot.imshow() object to numpy array?

查看:209
本文介绍了有没有一种方法可以将pyplot.imshow()对象转换为numpy数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要可视化2D numpy数组.我为此使用pyplot. 这是代码:

I need to visualize a 2D numpy array. I am using pyplot for this. Here's the code:

import cv2 as cv
import numpy as np
from matplotlib import pyplot

img = pyplot.imshow( radiance_val )
#radiance_val is a 2D numpy array of size = ( 512, 512 ) 
#filled with np.float32 values

pyplot.show()

我得到了预期的输出.

现在我的问题是,有什么方法可以将上述代码中的"img"从pyplot类型转换为numpy类型.我需要这样做,以便可以将可视化文件加载为opencv图像并对其进行进一步处理.我正在使用32位python 2.7.

Now my question is, is there any way of converting "img" in the above code from pyplot type to numpy type. I need this so that I can load the visualization as opencv image and perform further processing on it. Im am using python 2.7, 32 bit.

请帮助

谢谢

在Thorsten Kranz解决方案之后

EDIT 1: after Thorsten Kranz's solution

import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
import PIL
from cStringIO import StringIO

frame1 = plt.gca()
frame1.axes.get_xaxis().set_visible(False)
frame1.axes.get_yaxis().set_visible(False)
plt.imshow(np.random.random((10,10)))

buffer_ = StringIO()
plt.savefig( buffer_, format = "png", bbox_inches = 'tight', pad_inches = 0 )
buffer_.seek(0)

image = PIL.Image.open( buffer_ )

ar = np.asarray(image)
cv.imshow( 'a', ar )
cv.waitKey(0)
cv.destroyAllWindows()

在这里,我在程序终止后从MS VC ++运行时库收到运行时错误.我更好的猜测是因为打开了"buffer_".但是我得到了所需的输出.

Here I am getting a runtime error from MS VC++ runtime library after the program terminates. My better guess is that it is because of the open "buffer_". But I am getting the required output.

使用

buffer_.close()

没有解决运行时错误

最终编辑:推荐答案

除非您确实需要标记滴答声等,

Unless you really need the marker ticks and such,

im._rgba_cache

使您可以直接访问作为颜色映射数据的MxNx4 numpy数组.

gives you direct access to the MxNx4 numpy array that is the color mapped data.

如果只需要颜色映射的数据,则可以完全传递imshow并直接对自己的数据进行颜色映射(请参见指南(选择颜色图)

If you just want the color mapped data, you can by pass imshow entirely and directly color-map the data your self (see guide for picking your color map)

my_cm = maplotlib.cm.get_cmap('Reds')
normed_data = (data - np.min(data)) / (np.max(data) - np.min(data))
mapped_data = my_cm(normed_data)

这将带您返回映射在01之间的MxNx4数组,

which will give you back a MxNx4 array mapped between 0 and 1,

mapped_datau8 = (255 * my_cm(normed_data)).astype('uint8')

mapped_data = my_cm(normed_data, bytes=True)

会将其转换为无符号整数.

will convert it to unsigned ints.

matplotlib包括一系列规范化代码,请参阅这里.

matplotlib includes a range of normalization code, see here.

get_cmap文档已在 https://stackoverflow.com/a/14880947/380231

这篇关于有没有一种方法可以将pyplot.imshow()对象转换为numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆