I have a 16-bit grayscale image and I want to convert it to an 8-bit grayscale image in OpenCV for Python to use it with various functions (like findContours
etc.). How can I do this in Python?
Pixelate. This is another image manipulation package for Python which can be used to pixelate or convert normal images to 8-bit images. The module is very handy and comes with a lot of other functionalities like image resize, grayscaling, etc.
In general there is no way back from 8bit to 16bit. With 8bit images you can have 256 shades of gray, with 16bit you may have 65536 shades of gray. So if you have a 16bit image that shows more than 256 shades of gray and you convert it to 8bit, you definitely loose gray-levels.
Simply head to Image -> Mode -> 16bit, to convert your Photoshop document to a 16 bit file. By doing this this at the start of your work, any edits you make to images in this document will have the benefit of 16bit colour.
You can use numpy conversion methods as an OpenCV mat is a numpy array.
This works:
img8 = (img16/256).astype('uint8')
Opencv provides the function cv2.convertScaleAbs()
image_8bit = cv2.convertScaleAbs(image, alpha=0.03)
Alpha is just a optional scale factor. Also works for multiple channel images.
OpenCV documentation:
Scales, calculates absolute values, and converts the result to 8-bit.
On each element of the input array, the function convertScaleAbs performs three operations sequentially: scaling, taking an absolute value, conversion to an unsigned 8-bit type:
Other Info on Stackoverflow: OpenCV: How to use the convertScaleAbs() function
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