Ask Your Question
1

How to crop non rectangular area from Mat?

asked 2014-09-01 15:48:39 -0600

densvr gravatar image

updated 2015-08-25 19:50:10 -0600

Hello everybody,

I need some help with cropping cv::Mat. There are a src mat image and a polygon to be cropped (for example triangle). For cropping I create mask image having size like src mat one and depth CV_8U. Then I filled my mask with 0 value and draw polygon on it using cv::filimage descriptionlPoly function . Finally, I try to apply the mask to src image using Mat::copyTo function but nothing happens with src img. What I do wrong?

Sorry for my bad English.

here is a part of my code

Mat createMask(const Size &size, const vector<Point2f> &_pts) {
    vector<Point> pts(_pts.size());
    for(int i = 0; i < _pts.size(); i++) {
        pts[i] = _pts[i];
    }
    const Point* elementPoints[1] = { &pts[0] };
    int numPoints = (int)pts.size();
    Mat mMask = Mat::zeros(size, CV_8U);
    mMask.setTo(255);
    //circle(mMask, Point(30,30), 20, Scalar(0), 0);
    fillPoly(mMask, elementPoints, &numPoints, 1, Scalar(0));
    imshow("mMask", mMask);
    return mMask;
}

Mat mMask = createMask(size, pts); //some cv::Size and some predefined polygon points
Mat mTmp = mSrc.clone();
mTmp.copyTo(mSrc, mMask);
imshow("debug_frame", mFrame);
waitKey();
edit retag flag offensive close merge delete

Comments

1

This) helped me alot. In opencv you have cv::bitwise_[and/or/xor/not] function.

boaz001 gravatar imageboaz001 ( 2014-09-02 02:48:30 -0600 )edit

I do not think that you can have a Mat that is not rectangular, so the best way is to find the minimum bounding rectangle and have just that region.

thdrksdfthmn gravatar imagethdrksdfthmn ( 2014-09-02 03:28:24 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
1

answered 2014-09-02 04:28:04 -0600

Hi @densvr!

If you want to mask only a part of one image into another image, you can do that by this method.

Mat Source = imread("S1.jpg", 1);
Mat mMask = imread("Smask.bmp",0); This is your Create mask output.
Mat Destination;
Source.copyTo(Destination,mMask);
imshow("Destination",Destination);

In your code you are displaying some other Mat(mFrame which is not altered) in the Window. Please read This wiki then this http://answers.opencv.org/faq/

edit flag offensive delete link more

Comments

Please mark as answer or Vote Up if this helps you.

Balaji R gravatar imageBalaji R ( 2014-09-03 04:22:35 -0600 )edit

Question Tools

Stats

Asked: 2014-09-01 15:48:39 -0600

Seen: 12,266 times

Last updated: Sep 02 '14