Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I convert a float32 image to an uint8 image?

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.

like image 617
Hamidreza Avatar asked Nov 10 '18 02:11

Hamidreza


People also ask

How do I convert an image to uint16?

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.


Video Answer


1 Answers

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)
like image 142
John_Sharp1318 Avatar answered Sep 22 '22 19:09

John_Sharp1318