Home > database >  Losing information when saving an image as uint8
Losing information when saving an image as uint8

Time:11-25

So I have an image, I'm just testing it with any random Google image, that I saved as "Picture.png". Now I want to normalize that image and save it as an .npy file, so I use the code:

from PIL import Image
import numpy as np

temp = Image.open("Picture.png")
image = np.asarray(temp)

def NormalizeData(data):
    return ((data - np.min(data)) / (np.max(data) - np.min(data)))

image = NormalizeData(image)
np.save("Picture.npy", image)

Then, I can retrieve the image with the code:

import matplotlib.pyplot as plt

image = np.load("Picture.npy")
plt.imshow(image)
plt.show()

The problem is that the .npy file is too big, so I added .astype('uint8') to the NormalizeData function, which saves tons of space. But now, when I try to plt.show() on the new uint8 .npy file, I get a white canvas.

What am I doing wrong?

CodePudding user response:

you are normalizing the data to be between 0 and 1, then you are converting it to an integer. which will round all numbers to 0.

you should just multiply the numbers by 255 before using the astype(np.uint8) so numbers will be between 0 and 255 which is the correct range for unsigned 8 bit integers.

  • Related