1

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.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Matblanket
  • 55
  • 4

2 Answers2

2

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)
AKX
  • 152,115
  • 15
  • 115
  • 172
  • There's no guarantee that the values -1 or -0.85 will be in the image, so `np.min` and `np.max` doesn't necessarily work here – QWERTYL Apr 02 '22 at 17:43
  • @QWERTYL I interpreted OP's message to say that the actual range already is -1 to -.85 - but sure, `arr_min` and `arr_max` could be hard-coded :) – AKX Apr 02 '22 at 17:44
0

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.

FirefoxMetzger
  • 2,880
  • 1
  • 18
  • 32