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