OpenCV提供了一些基本的形态学处理方法与绘图操作,比如膨胀、腐蚀、开闭操作、画圆,画椭圆,画线,画矩形,在图像里插入文字等功能。
代码:
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <math.h>
#include <iostream>
using namespace std;
using namespace cv;
//double threshold = 200.0;
Mat BinaryImg,morhImage;
int main()
{
Mat img = imread("../img/33.png", IMREAD_GRAYSCALE);
imshow("原图", img);
threshold(img , BinaryImg ,0 ,255,THRESH_BINARY |THRESH_OTSU);
imshow("二值化",BinaryImg);
//形态学处理
Mat kernel = getStructuringElement(MORPH_RECT, Size(4, 4));
morphologyEx(BinaryImg, morhImage, MORPH_OPEN, kernel); //去掉杂点
imshow("形态学结果", morhImage);
vector<vector<Point>> contours;
Mat resutimg = Mat::zeros(img.size(),CV_8UC3);
findContours(morhImage, contours, RETR_TREE, CHAIN_APPROX_SIMPLE); //找到图像轮廓
for (int i = 0; i < contours.size(); i++)
{
double area = contourArea(contours[i]); //去掉小区域
if(area < 100 ) continue;
Rect rect = boundingRect(contours[i]); //根据外轮廓长宽比率寻找圆
float ratio = (float)(rect.width) / rect.height;
if (ratio > 0.9 && ratio < 1.1)
{
drawContours(resutimg, contours, i, Scalar(0, 0, 250),-1); //找到圆的轮廓,-1代表填充
int x = rect.x + rect.width / 2;
int y = rect.y + rect.height / 2;
//circle(resutimg, Point(x, y), 2, Scalar(0, 0, 250),2); //画小圆点
cout << "circle area : " << area << endl;
cout << "circle length : " << arcLength(contours[i], true);
cout << "circle center : x= " << x<<" , y = "<< y << endl;
}
}
imshow("result", resutimg); //绘制圆的轮廓与圆心
waitKey(0);
}
结果: