如何在OpenCV中裁剪CvMat?

时间:2011-11-25 09:47:10

标签: opencv opencv-mat

我的图像转换为CvMat矩阵CVMat source。一旦我从source获得感兴趣的区域,我希望算法的其余部分仅应用于该感兴趣的区域。为此我想我将不得不以某种方式裁剪source矩阵,我无法这样做。是否有方法或函数可以裁剪CvMat矩阵并返回另一个裁剪的CvMat矩阵?感谢。

6 个答案:

答案 0 :(得分:103)

OpenCV具有您感兴趣的感兴趣区域功能。如果您使用的是cv::Mat,那么您可以使用以下内容。

// You mention that you start with a CVMat* imagesource
CVMat * imagesource;

// Transform it into the C++ cv::Mat format
cv::Mat image(imagesource); 

// Setup a rectangle to define your region of interest
cv::Rect myROI(10, 10, 100, 100);

// Crop the full image to that image contained by the rectangle myROI
// Note that this doesn't copy the data
cv::Mat croppedImage = image(myROI);

Documentation for extracting sub image

答案 1 :(得分:35)

我知道这个问题已经解决了......但是有一种非常简单的方法可以裁剪。你可以在一行中完成 -

Mat cropedImage = fullImage(Rect(X,Y,Width,Height));

答案 2 :(得分:17)

为了获得针对不同类型矩阵的更好结果和稳健性,除了复制数据的第一个答案外,您还可以执行此操作:

cv::Mat source = getYourSource();

// Setup a rectangle to define your region of interest
cv::Rect myROI(10, 10, 100, 100);

// Crop the full image to that image contained by the rectangle myROI
// Note that this doesn't copy the data
cv::Mat croppedRef(source, myROI);

cv::Mat cropped;
// Copy the data into new matrix
croppedRef.copyTo(cropped);

答案 3 :(得分:3)

要创建我们想要的裁剪副本,我们可以执行以下操作,

// Read img
cv::Mat img = cv::imread("imgFileName");
cv::Mat croppedImg;

// This line picks out the rectangle from the image
// and copies to a new Mat
img(cv::Rect(xMin,yMin,xMax-xMin,yMax-yMin)).copyTo(croppedImg);

// Display diff
cv::imshow( "Original Image",  img );
cv::imshow( "Cropped Image",  croppedImg);
cv::waitKey();

答案 4 :(得分:1)

我理解这个问题已得到解答,但也许这对某些人可能有用......

如果您希望将数据复制到单独的 cv :: Mat 对象中,您可以使用与此类似的函数:

void ExtractROI(Mat& inImage, Mat& outImage, Rect roi){
    /* Create the image */
    outImage = Mat(roi.height, roi.width, inImage.type(), Scalar(0));

    /* Populate the image */
    for (int i = roi.y; i < (roi.y+roi.height); i++){
        uchar* inP = inImage.ptr<uchar>(i);
        uchar* outP = outImage.ptr<uchar>(i-roi.y);
        for (int j = roi.x; j < (roi.x+roi.width); j++){
            outP[j-roi.x] = inP[j];
        }
    }
}

重要的是要注意,这只能在单通道图像上正常运行。

答案 5 :(得分:-2)

您可以使用opencv功能轻松裁剪Mat。

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(TalentInfo model, IEnumerable<HttpPostedFileBase> files)
{
    if (ModelState.IsValid)
    {
        //you have lots of code here....
    }
    else
    {
        //you need to return something here....because (ModelState.IsValid) might be false
    }
}

setMouseCallback("Original",mouse_call); 如下:

mouse_call

有关详细信息,请访问链接Cropping the Image using Mouse

相关问题