C++和opencv实现在图像轮廓上打上字为缺陷标签代码
以下是使用C++和OpenCV在图像轮廓上打上“缺陷”标签的示例代码:
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
// 加载图像
Mat image = imread("input.jpg");
// 将图像转换为灰度图像
Mat gray;
cvtColor(image, gray, COLOR_BGR2GRAY);
// 使用Canny边缘检测算法检测边缘
Mat edges;
Canny(gray, edges, 50, 150);
// 找到轮廓
vector<vector<Point>> contours;
findContours(edges, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
// 在轮廓上打上标签
for (int i = 0; i < contours.size(); i++)
{
// 计算轮廓的面积
double area = contourArea(contours[i]);
// 如果面积小于1000,则认为是缺陷
if (area < 1000)
{
// 在轮廓上打上“缺陷”标签
Rect rect = boundingRect(contours[i]);
putText(image, "Defect", Point(rect.x, rect.y - 5), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 255), 2);
}
}
// 显示结果
imshow("Result", image);
waitKey(0);
return 0;
}
在此示例代码中,我们首先加载图像并将其转换为灰度图像。然后使用Canny边缘检测算法检测边缘,并找到轮廓。接下来,我们遍历每个轮廓,计算其面积,如果面积小于1000,则在轮廓上打上“缺陷”标签。最后,我们显示结果并等待用户按下任意键以退出程序
原文地址: https://www.cveoy.top/t/topic/cnKf 著作权归作者所有。请勿转载和采集!