用c opencv 写一段用Canny进行边缘检测,再用findContours进行轮廓检测,再用drawContours绘制轮廓,最后再用minAreaRect定位异常位置的代码
时间: 2023-08-04 10:29:51 浏览: 45
好的,以下是用Canny进行边缘检测,再用findContours进行轮廓检测,再用drawContours绘制轮廓,最后再用minAreaRect定位异常位置的代码:
```c
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
// 读入图像
Mat img = imread("test.jpg", IMREAD_GRAYSCALE);
// Canny边缘检测
Mat edges;
Canny(img, edges, 100, 200);
// 轮廓检测
vector<vector<Point>> contours;
findContours(edges, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
// 绘制轮廓
Mat draw = Mat::zeros(img.size(), CV_8UC3);
Scalar color = Scalar(0, 0, 255); // 红色
drawContours(draw, contours, -1, color, 2);
// 定位异常位置
for (size_t i = 0; i < contours.size(); i++)
{
RotatedRect rect = minAreaRect(contours[i]);
float w = rect.size.width;
float h = rect.size.height;
float ratio = w / h; // 计算宽高比
if (ratio > 2) // 如果宽高比大于2,认为是异常位置
{
Point2f pts[4];
rect.points(pts);
for (int j = 0; j < 4; j++)
{
line(draw, pts[j], pts[(j + 1) % 4], color, 2); // 绘制矩形框
}
}
}
// 显示结果
imshow("edges", edges);
imshow("draw", draw);
waitKey();
return 0;
}
```
注:以上代码是在OpenCV 4.5.2的环境下编写的,如果你的OpenCV版本较低,可能需要做出一些调整。