user2743
user2743

Reputation: 1513

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

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))

Upvotes: 2

Views: 5698

Answers (2)

Cris Luengo
Cris Luengo

Reputation: 60444

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.

Upvotes: 0

Pitto
Pitto

Reputation: 8579

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)))

Upvotes: 7

Related Questions