为什么.imshow()生成的像素比我输入的图像还要多? [英] Why is .imshow() producing images with more pixels than I have put in?

查看:32
本文介绍了为什么.imshow()生成的像素比我输入的图像还要多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 numpy 数组 A,形状为 (60,60,3),我正在使用:

I have a numpy array A, having a shape of (60,60,3), and I am using:

plt.imshow(  A,
             cmap          = plt.cm.gist_yarg,
             interpolation = 'nearest',
             aspect        = 'equal',
             shape         = A.shape
             )
plt.savefig( 'myfig.png' )

当我检查 myfig.png 文件时,我看到它是 1200x800 像素(彩色).

When I examine the myfig.png file, I see that it is 1200x800 pixels (in color).

这是怎么回事?我期待60x60的RGB图像.

What's going on here? I was expecting a 60x60 RGB image.

推荐答案

matplotlib 不直接处理像素,而是处理图形大小(以英寸为单位)和分辨率(每英寸点数,<代码>dpi)

matplotlib doesn't work directly with pixels but rather a figure size (in inches) and a resolution (dots per inch, dpi)

因此,您需要明确给出图形大小和 dpi.例如,您可以将图形大小设置为 1x1 英寸,然后将 dpi 设置为 60,以获得 60x60 像素的图像.

So, you need to explicitly give a figure size and dpi. For example, you could set your figure size to 1x1 inches, then set the dpi to 60, to get a 60x60 pixel image.

您还必须删除绘图区域周围的空白,您可以使用 subplots_adjust

You also have to remove the whitespace around the plot area, which you can do with subplots_adjust

import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(1,1))

A = np.random.rand(60,60,3)

plt.imshow(A,
           cmap=plt.cm.gist_yarg,
           interpolation='nearest',
           aspect='equal',
           shape=A.shape)

plt.subplots_adjust(left=0,right=1,bottom=0,top=1)

plt.savefig('myfig.png',dpi=60)

这创造了这个数字:

大小为 60x60 像素:

Which has a size of 60x60 pixels:

$ identify myfig.png 
myfig.png PNG 60x60 60x60+0+0 8-bit sRGB 8.51KB 0.000u 0:00.000

您还可以参考此答案,其中包含许多有关图形大小和分辨率的良好信息.

You might also refer to this answer, which has lots of good information about figure sizes and resolutions.

这篇关于为什么.imshow()生成的像素比我输入的图像还要多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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