Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a 16 bit to an 8 bit image in OpenCV?

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?

like image 272
pap-x Avatar asked Aug 25 '14 12:08

pap-x


People also ask

How do you convert an image to 8-bit 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.

Can you convert 8bit to 16bit?

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.

How do I convert an image to 16 bit?

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.


2 Answers

You can use numpy conversion methods as an OpenCV mat is a numpy array.

This works:

img8 = (img16/256).astype('uint8') 
like image 195
Vasanth Avatar answered Oct 09 '22 04:10

Vasanth


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

like image 26
Steven Avatar answered Oct 09 '22 03:10

Steven