1、概述
案例:输入一张图片找到图片中的一个圆,并标注圆心
实现步骤:
1.输入原图
2.图像图像灰度化
3.图像二值化
4.执行形态学操作去除噪点
5.边缘检测
6.轮廓发现
7.根据面积和纵横比过滤目标轮廓
8.找出圆心并绘制圆心
9.在原图上也绘制圆心并输出
2、代码示例
//【1】载入图像
Mat src = imread(filePath);
Mat src_clone = src.clone();
if(src.empty()){
qDebug()<<"图片为空";
return;
}
imshow("src",src);
//21】转灰度图
Mat gray;
cvtColor(src,gray,COLOR_BGR2GRAY);
//【3】图像二值化
threshold(gray,gray,0,255,THRESH_BINARY|THRESH_OTSU);
imshow("threshold",gray);
//【4】执行形态学开操作去除噪点
Mat kernel = getStructuringElement(MORPH_RECT,Size(20,20),Point(-1,-1));
morphologyEx(gray,gray,MORPH_OPEN,kernel,Point(-1,-1),1);
imshow("morphologyEx",gray);
//【5】边缘检测
Canny(gray,gray,0,255);
imshow("canny",gray);
//【6】轮廓发现
vector<vector<Point>> contours;
vector<Vec4i> her;
findContours(gray,contours,her,RETR_TREE,CHAIN_APPROX_SIMPLE);
Mat resultImage = Mat::zeros(gray.size(),CV_8UC3);
RNG rng(12345);
double area = 0.0;
Point pRadius;
for(size_t i = 0;i<contours.size();i++){
double area = contourArea(contours[i],false);
//【7】根据面积及纵横比过滤轮廓
if(area>200){
Rect rect = boundingRect(contours[i]);
float scale = float(rect.width)/float(rect.height);
if(scale<1.1&&scale>0.9){
drawContours(resultImage,contours,i,Scalar(rng.uniform(0,255),rng.uniform(0,255),rng.uniform(0,255)),-1);
int x = rect.width/2;
int y = rect.height/2;
//【8】找出圆心并绘制
pRadius=Point(rect.x+x,rect.y+y);
circle(resultImage,pRadius,2,Scalar(0,0,255),2);
}
}
}
imshow("resultImage",resultImage);
//【9】在原图上绘制圆心,这一步要不要都行,因为坐标都找出来了,可以随便标注
circle(src_clone,pRadius,2,Scalar(0,0,255),2);
imshow("src_clone",src_clone);
3、图片示例
本文福利,莬费领取Qt开发学习资料包、技术视频,内容包括(C++语言基础,Qt编程入门,QT信号与槽机制,QT界面开发-图像绘制,QT网络,QT数据库编程,QT项目实战,QSS,OpenCV,Quick模块,面试题等等)↓↓↓↓↓↓见下面↓↓文章底部点击莬费领取↓↓