【问题标题】:Problems with saving numpy array as an image将numpy数组保存为图像的问题
【发布时间】:2019-11-21 20:54:53
【问题描述】:

我无法将 numpy 二维数组保存为图像(灰度)。我读了这个问题Save plot to image file instead of displaying it using Matplotlib,但仍然不明白下面的代码有什么问题。

plt.imsave("image.eps", np.flipud(arr), cmap = "gray_r", format = "eps", dpi = 1000)

执行后 image.eps 是空白的,我不明白为什么。我也尝试将其作为 AxesImage 对象处理(见下文),但没有成功。

img = plt.imshow(np.flipud(arr))
plt.savefig("image.eps", format = "eps", dpi = 1000)

请解释一下这段代码有什么问题。

其实我是 Python 新手(对 matplotlib 也是如此),所以我对 Python 的很多想法并不熟悉。

更新: 我尝试了以下代码,但 image.eps 仍然是空白的。

import matplotlib.pyplot as plt
import numpy as np

arr = np.array([[1, 0.5],[0.5, 0]])

plt.imsave("image.eps", np.flipud(arr), cmap = "gray_r", format = "eps", dpi = 1000)

另一方面,如果我打电话

img = plt.imshow(arr)

然后我可以在控制台 (Spyder) 中看到正确的图片(一个黑色、一个白色和两个灰色方块)。

也许有一些方法可以使用 img 变量保存图片?

【问题讨论】:

  • 你能包含你正在使用的数组吗?或者至少是其中的一个子集?
  • 使用arr = np.arange(10000).reshape(100,100),您的imsave 语法有效(尽管图像只有1 英寸宽)。所以你需要更具体。
  • 我怀疑一个主要问题是 eps 与其他矢量格式一样,并没有真正定义 dpi。如果 72 的规范“dpi”与设置的 dpi(此处为 1000)完全不同,这可能会产生一些奇怪的含义。
  • 是的,确实,没有设置 dpi 的代码可以工作。但是,对应的图片太小了(即使是我使用的 500×500 的矩阵)。可以把图片放大吗?

标签: python matplotlib plot


【解决方案1】:

我已经在我的解释器中测试了imsave

In [39]: import numpy as np 
    ...: import matplotlib.pyplot as plt                                                  

In [40]: a = np.random.random((500,500))                                                  

In [41]: plt.imsave('a1000.eps', a, dpi=1000)                                             

In [42]: plt.imsave('a0500.eps', a, dpi=500)                                              

In [43]:                                                                                  
Do you really want to exit ([y]/n)? 
22:07 boffi@debian:~ $ ll a1000.eps a0500.eps 
-rw-r--r-- 1 boffi boffi 1512480 Nov 22 22:07 a0500.eps
-rw-r--r-- 1 boffi boffi 1512480 Nov 22 22:07 a1000.eps

如您所见,这两个文件的大小相同,是相等还是不同?

22:08 boffi@debian:~ $ diff a1000.eps a0500.eps 
2c2
< %%Title: a1000.eps
---
> %%Title: a0500.eps
4c4
< %%CreationDate: Fri Nov 22 22:07:30 2019
---
> %%CreationDate: Fri Nov 22 22:07:42 2019
6c6
< %%BoundingBox: 288.0 378.0 324.0 414.0
---
> %%BoundingBox: 270.0 360.0 342.0 432.0
31,32c31,32
< 288 378 translate
< 36 36 0 0 clipbox
---
> 270 360 translate
> 72 72 0 0 clipbox
37c37
< 36.0 36.0 scale
---
> 72.0 72.0 scale

如您所见,差异仅在于后记代码,尤其是scale 命令具有有趣的不同参数...相反我们看到表示矩阵的原始数据完全正确 两个文件相同。这与imsave文档字符串中dpi的描述一致

dpi : int
      The DPI to store in the metadata of the file.  This does not affect the
      resolution of the output image.

最后,我们遇到了您的图片是空白的问题。我的不是。请注意,较大的图像是具有较小dpi 的图像,这与您认为增加dpi 会得到更大图像的想法相反。

【讨论】:

    猜你喜欢
    • 2010-10-28
    • 2011-10-18
    • 1970-01-01
    • 2020-07-07
    • 2020-06-29
    • 2015-02-20
    • 2020-06-04
    • 2021-02-05
    相关资源
    最近更新 更多