Maha
Maha

Reputation: 21

Using image as a mask to another

I am a beginner with OpenCV and I have some questions:

How can I use one image as a mask to another image?

For example, I have an image contains empty circle, and another image contains a circle with content (not empty) and background.

How can i extract common parts of the two images in a new image?

I tried extracting a pixel by pixel to do the (AND) operation but it fails!

Can anybody help me to get some ideas!

I try the following code (that I found here) but it produces wrong result!

I tried it with binary image by replacing

CvScalar bgr = cvScalar(b, g, r);
cvSet2D(mask, iy+y, ix+x, bgr);

with

CvScalar bgr = cvScalar(b);
cvSet2D(mask, iy+y, ix+x, b);

void processImage(IplImage* mask, IplImage* source, int x, int y) {
    int b,g,r;
    for (int ix=0; ix<source->width; ix++) {
        for (int iy=0; iy<source->height; iy++) {
            //r = cvGet2D(source, iy, ix).val[2] * cvGet2D(mask, iy, ix).val[2];
            //g = cvGet2D(source, iy, ix).val[1] * cvGet2D(mask, iy, ix).val[1];;
            b = cvGet2D(source, iy, ix).val[0] * cvGet2D(mask, iy, ix).val[0];

            CvScalar bgr = cvScalar(b); //, g, r);
            cvSet2D(mask, iy+y, ix+x, b); //gr);
        }
    }
}

Upvotes: 1

Views: 677

Answers (1)

carnieri
carnieri

Reputation: 1353

If I understand correctly, you have a mask (binary image) and you want to AND it with your source image. Try this:

cvAnd(source, source, destination, mask)

That double source there is not a typo. You're just ANDing source with itself (a no-op), but only for those pixels in mask that are "on" (that is, != 0). Note that mask must be an 8-bit single channel image.

Upvotes: 2

Related Questions