【问题标题】:Why do I get a color noise map when I use an array of floats with imshow() but if I use uint8 I get the image I want?为什么当我使用带有 imshow() 的浮点数组时会得到颜色噪声图,但如果我使用 uint8 我会得到我想要的图像?
【发布时间】:2017-12-19 06:06:51
【问题描述】:
import numpy as np
import matplotlib.pyplot as plt

files = ### 100 portrait photos
imgs = [ plt.imread( f_i ) for f_i in files ] # We read all file compositions into imgs
data = np.array( imgs ) # Turn everything into np.array format
mean_imgs = np.mean( data, axis= 0) # Takes the mean of the entire data set

plt.imshow( mean_imgs ) # imgs_mean = array of floats

结果:

plt.imshow( mean_imgs.astype( np.uint8 ) ) # Cast mean_imgs into type uint

结果:

这可能更像是一个计算机视觉问题,无论如何我试图理解 imshow() 一个包含所有浮点数的数组和一个类型为 uint8 的数组之间的区别。有人可以向我解释这两个操作之间的后端发生了什么吗?

请忽略图片中的变量混淆。只需将它们视为具有不同类型的同一个变量。

【问题讨论】:

    标签: arrays python-3.x numpy matplotlib computer-vision


    【解决方案1】:

    Matplotlib 的 imshow 方法要求浮点数组的值介于 0.0 和 1.0 之间。否则,会发生一些截断(如溢出,除了超过 1),因此实际上只使用小数部分,从而导致您看到的噪音。

    如果您的浮点数在 0...255 范围内,您可以通过缩放它们来避免此问题:plt.imshow(X/255)

    例子:

    X = np.add.outer(np.add.outer(np.arange(0, 50, 0.3), np.arange(0, 50, 0.1)), np.arange(0, 60, 20))
    plt.imshow(X)
    

    plt.imshow(X/255)  #  same as imshow(X.astype(np.uint8))
    

    【讨论】:

      【解决方案2】:

      imshow documentation(强调我的):

      MxNx3 和 MxNx4 float 数组的每个组件的值应在 0.0 到 1.0 范围内。

      如果类型是 uint8,它期望值在 0 到 255 的范围内。

      由于转换为 uint8 会为您提供正确的结果,因此您的值显然不在 0.0 到 1.0 的范围内。

      这应该可行:

      plt.imshow( mean_imgs / 255 )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-06
        • 2019-11-10
        • 2019-06-04
        • 2017-05-15
        • 1970-01-01
        相关资源
        最近更新 更多