Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert image from CV_64F to CV_8U

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?

like image 346
Jazz Avatar asked Sep 17 '17 04:09

Jazz


2 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).

like image 117
Ani Aggarwal Avatar answered Oct 12 '22 11:10

Ani Aggarwal


You can convert it to a Numpy array.

import numpy as np

# Convert source image to unsigned 8 bit integer Numpy array
arr = np.uint8(image)

# Width and height
h, w = arr.shape

It seems OpenCV Python APIs accept Numpy arrays as well. I've not tested it though. Please test it and let me know the result.

like image 34
frogatto Avatar answered Oct 12 '22 11:10

frogatto