使用Matplotlib imshow() 显示缩放为1的图像(怎么做?)
我想用Matplotlib.pyplot的imshow()函数来显示一张图片(比如800x800像素),但是我希望这张图片的每一个像素在屏幕上也占用一个像素(也就是说,缩放比例是1,既不缩小也不放大)。
我还是个初学者,你知道该怎么做吗?
5 个回答
1
如果你在使用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)
7
如果你不太需要用到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数组。
31
Matplotlib这个工具并不是为了这个目的而优化的。如果你只是想把一张图片以1像素对1像素的方式显示出来,使用一些简单的选项会更好一点。(比如可以看看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()