【发布时间】:2011-12-24 18:45:44
【问题描述】:
我想用 Matplotlib.pyplot imshow() 函数显示一个图像(比如 800x800),但我想显示它,以便图像的一个像素占据屏幕上的一个像素(缩放因子 = 1,不缩小,不拉伸)。
我是初学者,你知道如何进行吗?
【问题讨论】:
标签: python matplotlib
我想用 Matplotlib.pyplot imshow() 函数显示一个图像(比如 800x800),但我想显示它,以便图像的一个像素占据屏幕上的一个像素(缩放因子 = 1,不缩小,不拉伸)。
我是初学者,你知道如何进行吗?
【问题讨论】:
标签: python matplotlib
Matplotlib 没有为此优化。如果您只想以一像素对一像素的方式显示图像,则使用更简单的选项会更好一些。 (例如,看看 Tkinter。)
说了这么多:
import matplotlib.pyplot as plt
import numpy as np
# DPI, here, has _nothing_ to do with your screen's DPI.
dpi = 80.0
xpixels, ypixels = 800, 800
fig = plt.figure(figsize=(ypixels/dpi, xpixels/dpi), dpi=dpi)
fig.figimage(np.random.random((xpixels, ypixels)))
plt.show()
或者,如果你真的想使用imshow,你需要更详细一点。但是,这具有允许您在需要时放大等优点。
import matplotlib.pyplot as plt
import numpy as np
dpi = 80
margin = 0.05 # (5% of the width/height of the figure...)
xpixels, ypixels = 800, 800
# Make a figure big enough to accomodate an axis of xpixels by ypixels
# as well as the ticklabels, etc...
figsize = (1 + margin) * ypixels / dpi, (1 + margin) * xpixels / dpi
fig = plt.figure(figsize=figsize, dpi=dpi)
# Make the axis the right size...
ax = fig.add_axes([margin, margin, 1 - 2*margin, 1 - 2*margin])
ax.imshow(np.random.random((xpixels, ypixels)), interpolation='none')
plt.show()
【讨论】:
glumpy。 code.google.com/p/glumpy 我认为pygame 也有很多类似的功能,如果你不想走成熟的 gui 工具包的路线。无论如何,祝你好运!
如果你真的不需要 matlibplot,这对我来说是最好的方法
import PIL.Image
from io import BytesIO
import IPython.display
import numpy as np
def showbytes(a):
IPython.display.display(IPython.display.Image(data=a))
def showarray(a, fmt='png'):
a = np.uint8(a)
f = BytesIO()
PIL.Image.fromarray(a).save(f, fmt)
IPython.display.display(IPython.display.Image(data=f.getvalue()))
使用showbytes() 显示图像字节字符串,使用showarray() 显示numpy 数组。
【讨论】:
如果您使用 Jupyter 笔记本,安装了 pillow(Python 图像库),并且不需要颜色图,那么 Image.fromarray 很方便。您只需要将数据转换为它可以使用的形式(np.uint8 或 bool):
import numpy as np
from PIL import Image
data = np.random.random((512, 512))
Image.fromarray((255 * data).astype(np.uint8))
或者如果你有一个布尔数组:
Image.fromarray(data > 0.5)
【讨论】:
如果您尝试放大图像,则:
import matplotlib.pyplot as plt
import numpy as np
dpi = 80
margin = 0.01 # The smaller it is, the more zoom you have
xpixels, ypixels = your_image.shape[0], your_image.shape[1] ##
figsize = (1 + margin) * ypixels / dpi, (1 + margin) * xpixels / dpi
fig = plt.figure(figsize=figsize, dpi=dpi)
ax = fig.add_axes([margin, margin, 1 - 2*margin, 1 - 2*margin])
ax.imshow(your_image)
plt.show()
【讨论】: