Friday, 4 October 2013

Converting 16-bit images to 8-bit images in OpenCV

Here is a simple example to convert 16-bit images to 8-bit images in OpenCV (for a single pixel). Note that the conversion is lossy.
// the original depth image is 16-bit (IPL_DEPTH_16U)
IplImage *dimg_original = cvLoadImage( filename, CV_LOAD_IMAGE_UNCHANGED );
CvScalar s = cvGet2D(dimg_original, 0, 0);
printf("16-bit depth value is %d, ",(int)s.val[0]);

// convert the original 16-bit depth image into 8-bit
IplImage *dimg = cvCreateImage(cvGetSize(dimg_original), IPL_DEPTH_8U,dimg_original->nChannels);
cvConvertScale(dimg_original, dimg, 1./40); //40 is the scaling factor to map 16-bit into 8-bit
CvScalar s1 = cvGet2D(dimg, 0, 0);
printf("8-bit depth value is %d\n",(int)s1.val[0]);
A few notes:
1. index in cvGet2D() and cvSet2D() starts with zero, and is in column-major order, i.e., cvGet2D(img, y, x)
2. If the scaling factor is greater than 1./256 (note that 65536 / 256 = 256, in the above example we set the factor to 1./40), pixels with larger values will all be mapped to 255 (no difference any more for larger values).
3. This method can also be used to convert 32-bit images to 8-bit images.

No comments:

Post a Comment