【问题标题】:Please let me know why image.fromarray in PIL is not running as plt.imshow in matplotlib请让我知道为什么 PIL 中的 image.fromarray 没有在 matplotlib 中作为 plt.imshow 运行
【发布时间】:2023-03-21 15:59:01
【问题描述】:

我尝试使用数组中的 image.fromarray 来显示图片,但我无法从 plt.imshow 中获得正确的图片。你有什么想法吗?

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

row,col,ch=img_array.shape
mean=0.0
sigma=20
gauss = np.array(np.random.normal(mean,sigma,(row,col,ch)),dtype=np.int64)
noisy = img_array + gauss
new_image = Image.fromarray(noisy,'RGB')
new_image

如果我通过 plt.imshow 运行它,请求的图片在下面

 plt.imshow(noisy, interpolation='nearest')
 plt.show()

【问题讨论】:

  • 因为类型是 int64,它不太适合只能处理 8/16 位样本的 PNG 文件。
  • @Mark Setchell 感谢我尝试了 int8 /int16 的回复,但仍然没有达到我的预期,您还有其他想法吗?
  • 我无法运行您的代码,因为我不知道 img_array 是什么。
  • 256X256 lena RGB 图像
  • 请确保您的代码最小、完整和可验证 - 请参阅stackoverflow.com/help/mcve 如果您让人们更容易运行您的代码,您将更有可能获得帮助.

标签: image matplotlib python-imaging-library


【解决方案1】:

您的类型太大 - int64

从以下位置更改行:

gauss = ...

到:

gauss = np.array(np.random.normal(mean,sigma,(row,col,ch)),dtype=np.int8)                  
noisy = (img_array + gauss).astype(np.uint8)                                               
Image.fromarray(noisy,'RGB').save('result.png') 

理想情况下,您也应该进行归一化,因为您将 0..255 范围内的像素添加到 -20..+20 范围内的一些噪声中,这意味着您将在某些点溢出 255。

【讨论】:

    猜你喜欢
    • 2021-02-10
    • 2022-08-21
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 2015-04-23
    相关资源
    最近更新 更多