【问题标题】:Why does changing the numpy.array dtype from int to float change the output of numpy.imshow()为什么将 numpy.array dtype 从 int 更改为 float 会更改 numpy.imshow() 的输出
【发布时间】:2020-07-08 04:14:06
【问题描述】:

今天,我遇到了一件我无法解释也找不到答案的奇怪事情。 也许我有一些基本的误解,我没有看到明显的东西,但我想我现在知道发生了什么,我会咬紧牙关被叫出来。

我正在使用 PIL 加载一些图像数据并将其转换为 numpy 数组。这里没有什么花哨的。 但是,我随后将数据类型从整数更改为浮点数,以便在后面的步骤中标准化 RGB 通道。

我希望将数据类型从 int 更改为 float 不会以任何方式真正改变图像。不过……

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

im = Image.open("test.jpg")

dtype 改变前:

plt.imshow(np.array(im))  

dtype 改变后:

plt.imshow(np.array(im).astype(float))    

这是人们所期望的吗?如果是这样……为什么?我错过了什么?

提前干杯和感谢!

【问题讨论】:

    标签: python numpy matplotlib python-imaging-library dtype


    【解决方案1】:

    如果您查看文档,您会看到 imshow 期望:

    • (M, N):带有标量数据的图像。使用标准化和颜色图将值映射到颜色。查看参数 norm、cmap、vmin、vmax。

    • (M, N, 3):具有 RGB 值(0-1 float 或 0-255 int)的图像。

    所以当 dtype 为 float 时,它希望它们在 0-1 范围内,因此我们必须将其除以 255 以获得预期结果,否则您将看到 负数 em> 图片。

    这是一个使用来自sklearn.datasets 的示例图像的示例:

    from sklearn.datasets import load_sample_images
    dataset = load_sample_images()     
    first_img_data = dataset.images[0]
    plt.imshow(first_img_data)
    

    为了限制0-1范围内的值,我们只需要除以255

    plt.imshow(first_img_data.astype(float)/255)
    

    【讨论】:

    • 为什么看到图片的负片?
    • 谢谢。当你这样解释时,它是有道理的。
    • 好吧@mad ...链接中的问题正是如此。这就是我看到自己的方式,这就是看到那个帖子的原因。我认为只是引导你去它是最简单的方法
    • 我不是在讽刺,但回头看,我发现没有其他方法可以阅读我的评论。再乘以 255 的效果确实是个问题。
    • 谢谢!呃,回想起来。
    【解决方案2】:

    matplotlib.pyplot.imshow函数中写了以下内容:

    Parameters:
            X : array-like or PIL image
                The image data. Supported array shapes are:
                - (M, N): an image with scalar data. The values are mapped to
                  colors using normalization and a colormap. See parameters *norm*,
                  *cmap*, *vmin*, *vmax*.
                - (M, N, 3): an image with RGB values (0-1 float or 0-255 int).
                - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int),
                  i.e. including transparency.
    

    这项工作适合你:

    plt.imshow(np.array(im).astype(float)/255)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-31
      • 2018-10-01
      • 2013-01-06
      • 2021-06-01
      • 2023-01-28
      • 2023-03-20
      • 1970-01-01
      相关资源
      最近更新 更多