Reputation: 161
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.
Upvotes: 14
Views: 56479
Reputation: 1039
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, 255, 0, 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)
Upvotes: 32
Reputation: 339
It is actually very simple:
img_uint8 = img_float32.astype(np.uint8)
Upvotes: -7