如何在OpenCV中裁剪CvMat?

Waq*_*qar 51 opencv opencv-mat

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

Chr*_*ris 117

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);
Run Code Online (Sandbox Code Playgroud)

提取子图像的文档

  • 这意味着它只创建对该图像区域的引用而不是副本.这意味着如果更改croppedImage,它也会更改imagesource.如果您不想要此行为,则可以显式创建副本. (5认同)
  • 你是什​​么意思,这不复制数据? (4认同)
  • @Sohaib 然后我们需要使用我们所谓的“掩码”,它通常可用作处理函数的额外参数。 (2认同)
  • 如果我调用 `image.release()`,`croppedImage` 会发生什么? (2认同)

MMH*_*MMH 37

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

Mat cropedImage = fullImage(Rect(X,Y,Width,Height));
Run Code Online (Sandbox Code Playgroud)

  • 从哪里获得`fullImage()`函数?编辑:没关系,这是`cv :: Mat`-图像本身...... (3认同)
  • 这是公认的最佳答案。 (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);
Run Code Online (Sandbox Code Playgroud)


Ree*_*rds 9

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

// 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();
Run Code Online (Sandbox Code Playgroud)