I want to convert a float32
image into uint8
image in Python using the openCV library. I used the following code, but I do not know whether it is correct or not.
Here I
is the float32
image.
J = I*255
J = J.astype(np.uint8)
I really appreciate if can you help me.
J = im2uint16( I ) converts the grayscale, RGB, or binary image I to uint16 , rescaling or offsetting the data as necessary. If the input image is of class uint16 , then the output image is identical.
If you want to convert an image from single precision floating point (i.e. float32) to uint8, numpy
and opencv
in python offers two convenient approaches.
If you know that your image have a range between 0 and 255 or between 0 and 1 then you can simply make the convertion the way you already do:
I *= 255 # or any coefficient
I = I.astype(np.uint8)
If you don't know the range I suggest you to apply a min max normalization
i.e. : (value - min) / (max - min)
With opencv you simply call the following instruction :
I = cv2.normalize(I, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
The returned variable I type will have the type np.uint8
(as specify by the last argument) and a range between 0 and 255.
Using numpy
you can also write something similar:
def normalize8(I):
mn = I.min()
mx = I.max()
mx -= mn
I = ((I - mn)/mx) * 255
return I.astype(np.uint8)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With