您可以使用一个Rect 或两个Range 获取子图像(请参阅OpenCV doc)。
Mat3b img = imread("path_to_image");
图片:
Rect r(100,100,200,200);
Mat3b roi3b(img(r));
只要不更改图像类型,您就可以使用roi3b。所有的变化都会反映在原图img:
GaussianBlur(roi3b, roi3b, Size(), 10);
模糊后的图像:
如果您更改类型(例如,从 CV_8UC3 更改为 CV_8UC1),您需要处理深层副本,因为 Mat 不能有混合类型。
Mat1b roiGray;
cvtColor(roi3b, roiGray, COLOR_BGR2GRAY);
threshold(roiGray, roiGray, 200, 255, THRESH_BINARY);
您始终可以将结果复制到原始图像上,注意纠正类型:
Mat3b roiGray3b;
cvtColor(roiGray, roiGray3b, COLOR_GRAY2BGR);
roiGray3b.copyTo(roi3b);
阈值后的图像:
完整代码供参考:
#include <opencv2\opencv.hpp>
using namespace cv;
int main(void)
{
Mat3b img = imread("path_to_image");
imshow("Original", img);
waitKey();
Rect r(100,100,200,200);
Mat3b roi3b(img(r));
GaussianBlur(roi3b, roi3b, Size(), 10);
imshow("After Blur", img);
waitKey();
Mat1b roiGray;
cvtColor(roi3b, roiGray, COLOR_BGR2GRAY);
threshold(roiGray, roiGray, 200, 255, THRESH_BINARY);
Mat3b roiGray3b;
cvtColor(roiGray, roiGray3b, COLOR_GRAY2BGR);
roiGray3b.copyTo(roi3b);
imshow("After Threshold", img);
waitKey();
return 0;
}