为什么Mat的尺寸不同?

时间:2017-07-26 16:04:27

标签: c++ opencv crop opencv3.0 roi

我尝试从图像中裁剪出一个非矩形的Mat。遵循了很多教程,现在我为了我的目的实现了这个方法:

void crop(Mat src) {
Scalar mu, sigma;
meanStdDev(src, mu, sigma);

Canny(src, dst, mu.val[0] - sigma.val[0], mu.val[0] + sigma.val[0], 3, false);
cvtColor(dst, cdst, CV_GRAY2BGR);

HoughLinesP(dst, lines, 1, CV_PI / 2, 100, 50, 100);

Vec4i current, previous;
Point pt1, pt2, ppt1, ppt2;

for (size_t i = 1; i < lines.size(); i++) {
    current = lines[i];
    pt1 = Point(current[0], current[1]);
    pt2 = Point(current[2], current[3]);

    previous = lines[i - 1];
    ppt1 = Point(previous[0], previous[1]);
    ppt2 = Point(previous[2], previous[3]);

    vector<Point> pt;
    pt.push_back(Point(previous[2], previous[3]));                              
    pt.push_back(Point(previous[0], previous[1]));
    pt.push_back(Point(current[0], current[1]));
    pt.push_back(Point(current[2], current[3]));

    Rect roi = boundingRect(pt);    
    contourRegion = src(roi);

    Mat mask = Mat::zeros(contourRegion.size(), CV_8UC3);
    vector<Point> ROI_Poly;
    approxPolyDP(pt, ROI_Poly, 1.0, true);
    fillConvexPoly(mask, &ROI_Poly[0], ROI_Poly.size(), 255, 8, 0);

    Mat result = Mat(contourRegion.size(), CV_8UC3);
    try {
        src.copyTo(result, mask);
        imshow("result", result);
        imshow("contReg", contourRegion);
    } catch (Exception e) {}
}

编译后我得到例外:OpenCV Error: Assertion failed (size() == mask.size()) in cv::Mat::copyTo但为什么?实际上我将Mat&#39;设置为contourRegion.size所以它应该是同一个?

作为参考,这里是原始图片:enter image description here

1 个答案:

答案 0 :(得分:-1)

初步回答错了。这是修复

copyTo中,掩码可以方便地指示需要复制哪些矩阵元素,因此必须与源src具有相同的大小。请参阅文档here。此外,你的面具必须激活所有三个通道。因此,以下代码应该起作用:

int main(int argc, char **argv)
{
vector<Point> pt;
pt.push_back(cv::Point(10, 10));
pt.push_back(cv::Point(100, 20));
pt.push_back(cv::Point(200, 300));
pt.push_back(cv::Point(10, 120));
cv::Mat src = cv::imread(argv[1]);

Rect roi = boundingRect(pt);
cv::Mat contourRegion = src(roi);

Mat mask = Mat::zeros(contourRegion.size(), CV_8UC3);
vector<Point> ROI_Poly;
approxPolyDP(pt, ROI_Poly, 1.0, true);
fillConvexPoly(mask, &ROI_Poly[0], ROI_Poly.size(), 255, 8, 0);
cv::Mat f_mask = cv::Mat(src.size(), CV_8UC3);
f_mask.setTo(0);

// duplicate the mask on three channels
cv::Mat bgr_mask[3];
split(mask,bgr_mask);
cv::Mat in[] = {bgr_mask[0],bgr_mask[0],bgr_mask[0]};
cv::merge(in, 3, mask);

// copy the mask to a "full mask" of the same size as the image
mask.copyTo(f_mask(roi));

Mat result = Mat(src.size(), CV_8UC3);
try {
    src.copyTo(result, f_mask);
    imshow("result", result);
    imshow("src", src);
    cv::imshow("contReg", contourRegion);
    cv::waitKey(0);

} catch (Exception e) {}

return 0;
}

在众所周知的lena picture上,它给出了: enter image description here

要获得与contourRegion大小相同的结果,请使用:

imshow("result", result(roi));

你有:

enter image description here