Convert Images from [-1; 1] to [0; 255]

convert images from [-1; 1] to [0; 255]

As you have found, img * 255 gives you a resulting range of [-255:255], and (img + 1) * 255 gives you a result of [0:510]. You're on the right track.

What you need is either: int((img + 1) * 255 / 2) or round((img + 1) * 255 / 2). This shifts the input from [-1:1] to [0:2] then multiplies by 127.5 to get [0.0:255.0].

Using int() will actually result in [0:254]

How to convert 0-1 image float array to 0-255 int array

  • The issue is photo*=255 is still an array of floats.
    • Look at the photo array.
    • Add photo = photo.astype(int) after photo*=255.
    • X in .imshow should be int type when the array is 0-255: (M, N, 3): an image with RGB values (0-1 float or 0-255 int)
photo = plt.imread('Feynman.png')

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 5))

print(photo[0][0])

ax1.imshow(photo)

photo*=255

print(photo[0][0])

photo = photo.astype(int)

print(photo[0][0])

ax2.imshow(photo)

[output]:
[0.16470589 0.16470589 0.16470589]
[42. 42. 42.]
[42 42 42]

Sample Image

Change pixel intensity range from [0,255] to [0,1]

An opencv image is just a numpy array. You can thus convert the type to a float (or another number type that can work with fractional numbers), and then divide by 255.

So if you have an image a, then you can convert it with:

b = a.astype(float) / 255

How do I normalize the pixel value of an image to 0~1?

import numpy as np

data = np.random.normal(loc=0, scale=1, size=(96108, 7, 7))
data_min = np.min(data, axis=(1,2), keepdims=True)
data_max = np.max(data, axis=(1,2), keepdims=True)

scaled_data = (data - data_min) / (data_max - data_min)

EDIT: I have voted for the other answer since that is a cleaner way (in my opinion) to do it, but the principles are the same.

EDIT v2: I saw the comment and I see the difference. I will rewrite my code so it is "cleaner" with less extra variables but still correct using min/max:

data -= data.min(axis=(1,2), keepdims=True)
data /= data.max(axis=(1,2), keepdims=True)

First the minimum value is moved to zero, thereafter one can take the maximum value to get the full range (max-min) of the specific image.

After this step np.array_equal(data, scaled_data) = True.



Related Topics



Leave a reply



Submit