如何使用c++和opencv识别图中的矩形区域,并给出代码
时间: 2024-05-08 10:19:35 浏览: 12
您好,以下是使用 C++ 和 OpenCV 识别图像中的矩形区域的代码:
```
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv )
{
if ( argc != 2 )
{
printf("usage: %s <Image_Path>\n", argv[0]);
return -1;
}
// 读取图像
Mat image;
image = imread( argv[1], 1 );
if ( !image.data )
{
printf("No image data \n");
return -1;
}
// 转换成灰度图像
Mat gray;
cvtColor( image, gray, COLOR_BGR2GRAY );
// 阈值分割
Mat thresh;
threshold( gray, thresh, 127, 255, THRESH_BINARY );
// 查找轮廓
std::vector<std::vector<Point> > contours;
std::vector<Vec4i> hierarchy;
findContours( thresh, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) );
// 绘制轮廓
Mat contours_image = Mat::zeros( image.size(), CV_8UC3 );
for ( int i = 0; i< contours.size(); i++ )
{
drawContours( contours_image, contours, i, Scalar(0, 0, 255), 2, 8, hierarchy, 0, Point() );
}
// 显示结果
namedWindow( "Contours", WINDOW_AUTOSIZE );
imshow( "Contours", contours_image );
waitKey(0);
return 0;
}
```
该代码将读取指定的图像,将其转换为灰度图像,并通过阈值分割得到二值图像。然后,它将查找轮廓并绘制这些轮廓。最后,它将显示绘制好的图像。
请注意,这个代码只是从图像中找到了轮廓,并没有得到具体的矩形区域。如果您需要找到矩形区域,请在轮廓检测之后使用 `minAreaRect()` 函数来得到矩形区域。
希望这可以帮助您!