如何裁剪具有与源图像边界重叠的矩形的打开的 CV 矩阵

How do I crop an open CV matrix with an rectangle that overlaps the boundary of the source image

本文关键字:重叠 边界 矩阵 CV 图像 何裁剪 裁剪      更新时间:2023-10-16

裁剪矩阵的实现中有一个断言,可以防止cropRect与源图像的边缘重叠。

// Asserts that cropRect fits inside the image's bounds.
cv::Mat croppedImage = image(cropRect); 

我想解除此限制,并能够使用位于图像外部的黑色像素来执行此操作。 这可能吗?

答案是:从技术上讲这是可能的,但你真的不想这样做。图像周围没有"黑色像素"。你的"形象"只为自己分配了足够的内存,仅此而已。因此,如果您尝试访问分配内存之外的像素,则会出现运行时错误。如果你想有一些黑色像素,你必须按照@ffriend描述的方式自己做。image(cropRect) 没有分配任何东西,它只是创建指向已经存在的内存的新指针。

如果你仍然对如何完成这种裁剪感到好奇,OpenCV正在执行以下操作:

// check that cropRect is inside the image
if ((cropRect & Rect(0,0,image.cols,image.rows)) != cropRect)
    return -1; // some kind of error notification
// use one of Mat constructors (x, y, width and height are taken from cropRect)
Mat croppedImage(Size(width,height), image.type(), image.ptr(y)+x, image.step);

您可以跳过测试并进入初始化,但正如我所说,这是灾难的好方法。