Display image with a zoom = 1 with Matplotlib imshow() (how to?)

匿名 (未验证) 提交于 2019-12-03 02:49:01

问题:

I want to display an image (say 800x800) with Matplotlib.pyplot imshow() function but I want to display it so that one pixel of the image occupies one pixel on the screen (zoom factor = 1, no shrink, no stretch).

I'm a beginner, so do you know how to proceed?

回答1:

Matplotlib isn't optimized for this. You'd be a bit better off with simpler options if you just want to display an image at one-pixel-to-one-pixel. (Have a look at Tkinter, for example.)

That having been said:

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() 

Or, if you really want to use imshow, you'll need to be a bit more verbose. However, this has the advantage of allowing you to zoom in, etc if desired.

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() 


回答2:

If you don't really need matlibplot, here is the best way for me

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())) 

use showbytes() for show a image bytes string, and showarray() for show a numpy array.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!