Trying to normalize Python image getting error - RGB values must be in the 0..1 range

╄→гoц情女王★ 提交于 2021-02-08 04:41:07

问题


I'm given an image (32, 32, 3) and two vectors (3,) that represent mean and std. I'm trying normalize the image by getting the image into a state where I can subtract the mean and divide by the std but I'm getting the following error when I try to plot it.

ValueError: Floating point image RGB values must be in the 0..1 range.

I understand the error so I'm thinking I'm not performing the correct operations when I try to normalize. Below is the code I'm trying to use normalize the image.

mean.shape #(3,)
std.shape #(3,)
sample.shape #(32,32,3)

# trying to unroll and by RGB channels
channel_1 = sample[:, :, 0].ravel()
channel_2 = sample[:, :, 1].ravel()
channel_3 = sample[:, :, 2].ravel()

# Putting the vectors together so I can try to normalize
rbg_matrix = np.column_stack((channel_1,channel_2,channel_3))

# Trying to normalize
rbg_matrix = rbg_matrix - mean
rbg_matrix = rbg_matrix / std

# Trying to put back in "image" form
rgb_image = np.reshape(rbg_matrix,(32,32,3))

回答1:


Your error seems to point to a lack of normalization of the image.

I've used this function to normalize images in my Deep Learning projects

def normalize(x):
    """
    Normalize a list of sample image data in the range of 0 to 1
    : x: List of image data.  The image shape is (32, 32, 3)
    : return: Numpy array of normalized data
    """
    return np.array((x - np.min(x)) / (np.max(x) - np.min(x)))



回答2:


Normalizing an image by setting its mean to zero and its standard deviation to 1, as you do, leads to an image where a majority, but not all, of the pixels are in the range [-2,2]. This is perfectly valid for further processing, and often explicitly applied in certain machine learning methods. I have seen it referred to as "whitening", but is more properly called a standardization transform.

It seems that the plotting function you use expects the image to be in the range [0,1]. This is a limitation of the plotting function, not of your normalization. Other image display functions would be perfectly able to show your image.

To normalize to the [0,1] range you should not use the mean and standard deviation, but the maximum and the minimum, as shown in Pitto's answer.



来源:https://stackoverflow.com/questions/49429734/trying-to-normalize-python-image-getting-error-rgb-values-must-be-in-the-0-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!