How to convert a float32 img to uint8 where range is(-1 to -0.85)?

Viewed 166

I want to convert a float32 image into uint8 image in Python. I tried using the following code, but the output image only has values like 2 and 3 so the image is practically black.

gen_samples[0] * 255).round().astype(np.uint8)

When I try displaying the float32 image I get a blackish/greyish image where I can somewhat make out the required image.

2 Answers

Normalize the array to 0..1 first.

Assuming gen_samples is the image matrix:

arr_min = np.min(gen_samples)
arr_max = np.max(gen_samples)
gen_samples = (gen_samples - arr_min) / (arr_max - arr_min)

Since you tagged the question using scikit-image you are probably using skimage. In this case img_as_ubyte should do the trick:

from skimage.util import image_as_ubyte

img = img_as_ubyte(gen_samples[0])

Further, since you tagged the question with imageio-python I'll assume that the image data actually comes from some (binary) image format rather than being generated in the script. In this case, you can often use the backend that does the decoding and do the conversion while the image is being loaded. This is, however, specific to the format being used, so for a more specific answer you would have to provide more insight into where your images are coming from.

Related