Tom
Tom

Reputation: 990

How are OpenCV image masks used

How are image masks in OpenCV meant to be used? From my understanding I am using it correctly but am not getting the expected results.

I am trying to merge two images. I start out with a result Mat (original image) which looks like this:

enter image description here

I then want to add this new image on top:

enter image description here

To do this I create an image mask (with type 8UC1) that looks like this:

enter image description here

I then use the code image2.copyTo(result, mask); to copy the new image onto the result. In the code image2 is the new image and result is the original image.

The problem is the end result is just the new image, not the new image on top of the original image.

Code for merging the images:

//referenceImg is copied into the original image, 
referenceImg.copyTo(result);
cv::Mat mask = createMask(h, image2);

imshow("Result image before", result);

//Translate the image
//Before this image2 is a regular image loaded from disk 
cv::warpPerspective(image2, image2, h,
                        cv::Size(referenceImg.cols+image2.cols, referenceImg.rows*2), cv::INTER_CUBIC);


image2.copyTo(result, mask);
std::cout << mask.type() << std::endl; //Returns 0
imshow("Result", result);

cv::waitKey(0);

createMask method code:

cv::Mat App::createMask(cv::Mat homography, cv::Mat image)
{
    cv::Mat grayImage;
    image.copyTo(grayImage);
    grayImage.setTo(cv::Scalar(255, 255, 255));
    cv::cvtColor(grayImage, grayImage, CV_BGR2GRAY);

    cv::Mat mask;
    cv::warpPerspective(grayImage, mask, homography, cv::Size(image.cols*2, image.rows*2), cv::INTER_CUBIC);

    return mask;
}

Upvotes: 0

Views: 735

Answers (1)

lanpa
lanpa

Reputation: 1349

Looks like the size of image2 and result does not match.

So the copyTo function will allocate a new matrix for result matrix. (based on the size of image2)

reference

Upvotes: 1

Related Questions