convert image from CV_64F to CV_8U

Viewed 47165

I want to convert an image of type CV_64FC1 to CV_8UC1 in Python using OpenCV.

In C++, using convertTo function, we can easily convert image type using following code snippet:

image.convertTo(image, CV_8UC1);

I have searched on Internet but unable to find any solution without errors. Any function in Python OpenCV to convert this?

3 Answers

For those getting a black screen or lots of noise, you'll want to normalize your image first before converting to 8-bit. This is done with numpy directly as OpenCV uses numpy arrays for its images.

Before normalization, the image's range is from 4267.0 to -4407.0 in my case. Now to normalize:

# img is a numpy array/cv2 image
img = img - img.min() # Now between 0 and 8674
img = img / img.max() * 255

Now that the image is between 0 and 255, we can convert to a 8-bit integer.

new_img = np.uint8(img)

This can also be done by img.astype(np.uint8).

I faced similar issue and when I trying to convert the image 64F to CV_U8 I would end up with a black screen.

This link will help you understand the datatypes and conversion. Below is the code that worked for me.

from skimage import img_as_ubyte
cv_image = img_as_ubyte(any_skimage_image)
Related