【问题标题】:Global Centralize then Normalize Image全局集中然后标准化图像
【发布时间】:2020-06-05 00:51:57
【问题描述】:

我正在尝试使用全局集中图像

# example of global centering (subtract mean)
from numpy import asarray
from PIL import Image

# load image
image = Image.open('13.jpg')
pixels = asarray(image)

# convert from integers to floats
pixels = pixels.astype('float32')

# calculate global mean
mean = pixels.mean()
print('Mean: %.3f' % mean)
print('Min: %.3f, Max: %.3f' % (pixels.min(), pixels.max()))

# global centering of pixels
global_pixels = pixels - mean

# confirm it had the desired effect
mean = global_pixels.mean()
print('Mean: %.3f' % mean)
print('Min: %.3f, Max: %.3f' % (global_pixels.min(), global_pixels.max()))

然后使用中心化

# normalize to the range 0-1
pixels_new = global_pixels/ 255.0

# confirm the normalization
print('Min: %.3f, Max: %.3f' % (pixels_new.min(), pixels_new.max()))

plt.imshow(np.array(pixels_new))

plt.imsave('test1.png', pixels_new)

我收到一个警告,然后是一个错误

使用 RGB 数据将输入数据剪切到 imshow 的有效范围 ([0..1] 表示浮点数或 [0..255] 表示整数)。

然后在plt.imsave函数上

ValueError: 浮点图像 RGB 值必须在 0..1 范围内。

谁能解释一下哪里出了问题?

【问题讨论】:

    标签: python numpy matplotlib


    【解决方案1】:

    通过改变

    plt.imshow(np.array(pixels_new))
    

    plt.imshow(np.array(pixels* 255).astype(np.uint8))
    

    解决了这两个问题

    好像和这个https://github.com/matplotlib/matplotlib/issues/9391/有关

    最初来自here

    【讨论】:

      【解决方案2】:

      我更喜欢 opencv,因为它的粉丝群更大,并且更容易与 numpy 结合使用。我给你写了一个如何处理红色通道的简短示例,因为我假设你想分别平均所有三层,并分别为每个通道应用平均值:

      from numpy import asarray
      import cv2
      import numpy as np
      import matplotlib.pyplot as plt
      
      path="/content/111.jpg"
      
      # load image
      img=cv2.imread(path,1)
      
      # mean Pixel of Red layer
      mean_R=np.sum(img[:,:,0])/(img.shape[0]*img.shape[1])
      # Subtract calculated Mean_Red from all pixels
      img_red_new=img[:,:,0]-mean_R
      #eliminate all negative values
      img_red_new=(img_red_new>=0)*img_red_new
      
      
      # Validate Images and values
      plt.imshow(img_red_new)
      plt.figure()
      plt.imshow(img[:,:,0])
      print("Red_New:",np.max(img_red_new))
      print("Red_old:",np.max(img[:,:,0]))
      print("Mean:",mean_R)
      
      # Safe as Image
      cv2.imwrite("test.jpg",img_red_new)
      

      最后你的错误是因为你必须定义一个值范围,你的颜色在其中表示。在 0-1 或 0-255 之间,这是您的选择,但您必须选择一个。因此,只需通过以下方式标准化您的图像:

      max=np.max(image)
      image=image/max --> values 0-1
      

      此外,您可以通过以下方式将其转换回无符号整数 (0-255):

      image=image*255
      image=image.astype(np.uint8)
      

      【讨论】:

        猜你喜欢
        • 2015-03-13
        • 2019-05-01
        • 2022-01-12
        • 1970-01-01
        • 2015-12-10
        • 1970-01-01
        • 2016-10-27
        • 2017-03-31
        • 1970-01-01
        相关资源
        最近更新 更多