user227666
user227666

Reputation: 774

Divide Ipl image by a scalar in OpenCV

I am trying to divide 2 by all the matrix elements of an Ipl image using cvDiv with C API of OpenCV. My code is as follows:

IplImage* src = cvLoadImage(argv[1]);

CvMat*  src1 = cvCreateMat(src->height, src->width, CV_16UC3);

cvDiv(src, src1, double scale=2);

But, I am getting the following error:

  error: expected primary-expression before ‘double’

Can anybody tell why? Or is there any other way to divide all the elements of a matrix by a particular number say 2?

Upvotes: 1

Views: 2054

Answers (1)

hetepeperfan
hetepeperfan

Reputation: 4411

You can do it like this. But as I said it is quite diffucult and verbose to do this in the C-api but it is possible. In openCV C-Api it is really important that the matrices of the images are of the same type. Therefore you will not be able to do this with your

CvMat*  src1 = cvCreateMat(src->height, src->width, CV_16UC3);

but try it like this this works like a charm on my machine.

IplImage* src = cvLoadImage(argv[1]);
/*This ensures you'll end up with an image of the same type as the source image.
 *and it also will allocate the memory for you this must be done ahead.*/
IplImage* dest = cvCreateImage(
        cvSize(src->width, src->height),
        src->depth,
        src->nChannels
        );

/*we use this for the division*/
IplImage* div= cvCreateImage(
        cvSize(src->width, src->height),
        src->depth,
        src->nChannels
        );
/*this sets every scalar to 2*/
cvSet( div, cvScalar(2,2,2), NULL);
cvDiv( src, div, dest, 1 );

The above will get the job done using the C-api the same can be achieved with the following code using the C++-api and this is what I would recommend to anyone starting with opencv since I feel the C-api is much more verbose, and difficult. C++ matrix contructors and operator overloading make the task almost trivial:

cv::Mat Src2 = cv::imread( argv[1] );
cv::Mat Dest2 = Src2 / 2;

Upvotes: 5

Related Questions