OpenCV - 使用C ++从图像中裁剪非矩形区域 [英] OpenCV - Cropping non rectangular region from image using C++
问题描述
如何从图像裁剪非矩形区域?
How can I crop a non rectangular region from image?
想象一下,我有四个点,我想裁剪它,这个形状不会是一个三角形!
Imagine I have four points and I want to crop it, this shape wouldn't be a triangle somehow!
例如我有以下图片:
我想从图像中裁剪出来:
and I want to crop this from image :
我该怎么做?
问候..
How can I do this? regards..
推荐答案
裁剪任意四边形(或任何多边形)部分的过程image总结为:
The procedure for cropping an arbitrary quadrilateral (or any polygon for that matter) part of an image is summed us as:
- 生成掩码。你想要保留图像的面具是黑色,而你不想保留它的是白色。
- 计算输入图像和面具之间的bitwise_and
因此,我们假设你有一张图片。在整个过程中,为了简单起见,我将使用30x30的图像大小,您可以根据您的使用情况进行更改。
So, lets assume you have an image. Throughout this I'll use an image size of 30x30 for simplicity, you can change this to suit your use case.
cv::Mat source_image = cv::imread("filename.txt");
你有4个点想要用作角落:
And you have four points you want to use as the corners:
cv::Point corners[1][4];
corners[0][0] = Point( 10, 10 );
corners[0][1] = Point( 20, 20 );
corners[0][2] = Point( 30, 10 );
corners[0][3] = Point( 20, 10 );
const Point* corner_list[1] = { corners[0] };
您可以使用函数 cv :: fillPoly
在蒙版上绘制此形状:
You can use the function cv::fillPoly
to draw this shape on a mask:
int num_points = 4;
int num_polygons = 1;
int line_type = 8;
cv::Mat mask(30,30,CV_8UC3, cv::Scalar(0,0,0));
cv::fillPoly( mask, corner_list, &num_points, num_polygons, cv::Scalar( 255, 255, 255 ), line_type);
然后只需计算图像的bitwise_and并屏蔽:
Then simply compute the bitwise_and of the image and mask:
cv::Mat result;
cv::bitwise_and(source_image, mask, result);
结果
现在有裁剪的图像。如果你想让边缘变成白色而不是黑色,你可以改为:
result
now has the cropped image in it. If you want the edges to end up white instead of black you could instead do:
cv::Mat result_white(30,30,CV_8UC3, cv::Scalar(255,255,255));
cv::bitwise_and(source_image, mask, result_white, mask);
在这种情况下,我们使用 bitwise_and
's mask参数只能执行掩码中的bitwise_and。有关更多信息和所有链接,请参见本教程。我提到的功能。
In this case we use bitwise_and
's mask parameter to only do the bitwise_and inside the mask. See this tutorial for more information and links to all the functions I mentioned.
这篇关于OpenCV - 使用C ++从图像中裁剪非矩形区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!