Showing posts with label cpp. Show all posts
Showing posts with label cpp. Show all posts

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.

Thursday, 3 October 2013

C++ linking error with Linux 3.x

If you are linking your C/C++ program on Linux 3.x (e.g., Ubuntu 12.04), you may need to put the libraries at the end of the shell command, i.e.,
$(CC) -o $@ $+ $(OPT) $(LIBDIRS) $(LIBS)
(This is like if you use Makefile, same rule applies if you don't use Makefile)

For my example with OpenCV, here
INCLUDES = -I/usr/include/opencv
LIBS = -lcxcore -lcv -lcvaux -lhighgui -lml
LIBDIRS = -L/usr/lib
OPT = -O3 -Wno-deprecated
CC=g++
If you put $(LIBDIRS) and $(LIBS) earlier in this command, it would successfully link with earlier distros (I suppose those with Linux kernel version 2.x, such as Ubuntu 10.04), but not on the newer distros. As a result, you would get the following error message:
*****.cpp:(.text+0x2db3): undefined reference to `cvLoadImage'
*****.cpp:(.text+0x2ef7): undefined reference to `cvCreateImage'
*****.cpp:(.text+0x2feb): undefined reference to `cvCreateImage'
*****.cpp:(.text+0x3041): undefined reference to `cvConvertScale'
*****.cpp:(.text+0x3088): undefined reference to `cvSaveImage'
*****.cpp:(.text+0x3099): undefined reference to `cvReleaseImage'
*****.cpp:(.text+0x30ca): undefined reference to `cvReleaseImage'
*****.cpp:(.text+0x30f9): undefined reference to `cvReleaseImage'
That is, every function call in the libraries will end up with "undefined reference". Pretty tricky! I would appreciate if anyone points to me the stuff under the bonnet here.