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

查看:55
本文介绍了有没有办法将 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 图像并对其进行进一步处理.我正在使用 python 2.7,32 位.

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.

请帮忙

谢谢

编辑 1:在 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.

编辑 2:使用

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 doc色彩图库

https://stackoverflow.com/a/14880947/380231

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

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