如何使用c++和opencv识别图中矩形,并给出代码
时间: 2024-06-10 12:06:39 浏览: 245
可以使用OpenCV提供的矩形识别函数来完成该任务,具体代码如下:
```
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat image = imread("example.jpg", IMREAD_GRAYSCALE); // 读入图像
if (image.empty())
{
cout << "Could not open image file" << endl;
return -1;
}
// 高斯模糊以平滑图片
Mat blurred;
GaussianBlur(image, blurred, Size(3, 3), 0);
// Canny边缘检测
Mat edges;
Canny(blurred, edges, 50, 150);
// 寻找轮廓
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(edges, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
// 遍历轮廓并筛选矩形
for (int i = 0; i < contours.size(); i++)
{
double area = contourArea(contours[i]);
if (area > 100 && area < 10000) // 筛选面积在指定范围内的轮廓
{
vector<Point> approx;
approxPolyDP(contours[i], approx, arcLength(contours[i], true) * 0.05, true);
if (approx.size() == 4) // 判断是否为矩形
{
line(image, approx[0], approx[1], Scalar(0, 255, 0), 2);
line(image, approx[1], approx[2], Scalar(0, 255, 0), 2);
line(image, approx[2], approx[3], Scalar(0, 255, 0), 2);
line(image, approx[3], approx[0], Scalar(0, 255, 0), 2);
}
}
}
// 显示检测结果
imshow("Rectangles", image);
waitKey();
return 0;
}
```
该代码将读入名为“example.jpg”的图片,对其进行边缘检测并寻找轮廓,然后筛选面积在100到10000之间的轮廓,并判断其中是否为矩形,最后以绿色线条标识出所有矩形。注意:此代码仅仅是一份示例代码,实际使用时仍需要根据具体需求进行优化和修改。
阅读全文
相关推荐
















