版权声明:本文为博主原创文章,博主欢迎各位转载。 https://blog.csdn.net/tuwenqi2013/article/details/83718056
本案例主要完成对玉米颗粒数量的计算,由于颗粒存在重叠的现象,因此需要对这种情况进行一定的图像处理,分离出每个颗粒的轮廓。
代码:
#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;
int main()
{
Mat grayimg, BinaryImg, morhImage;
Mat img = imread("../img/44.png");
imshow("原图", img);
//二值化操作
cvtColor(img, grayimg, COLOR_BGR2GRAY);
threshold(grayimg, BinaryImg ,245 ,255,THRESH_BINARY );
imshow("二值化",BinaryImg);
//形态学腐蚀
Mat kernel = getStructuringElement(MORPH_RECT, Size(15,15));
dilate(BinaryImg ,morhImage,kernel);
imshow("morphology", morhImage);
//距离变换:用于二值化图像中的每一个非零点距自己最近的零点的距离,距离变换图像上越亮的点,代表了这一点距离零点的距离越远。
Mat dist;
bitwise_not(morhImage, morhImage);
distanceTransform(morhImage, dist, CV_DIST_L2, 3);
normalize(dist, dist, 0, 1.0, NORM_MINMAX); //范围在0~1之间
imshow("distance", dist);
//形态学处理
Mat MorphImg;
dist.convertTo(MorphImg, CV_8U);
threshold(MorphImg, MorphImg, 0.99, 255, THRESH_BINARY); //上面像素值在0~1之间
kernel = getStructuringElement(MORPH_RECT, Size(11, 11), Point(-1, -1));
morphologyEx(MorphImg, MorphImg, MORPH_OPEN, kernel); //开操作
imshow("t-distance" , MorphImg);
//找到种子的轮廓区域
vector<vector<Point>> contours;
findContours(MorphImg, contours, CV_RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
// draw result
Mat markers = Mat::zeros(img.size(), CV_8UC3);
RNG rng(12345); //随机产生颜色
for (int i = 0; i < contours.size(); i++)
{
drawContours(markers, contours, i, Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)), -1, 8, Mat());
}
cout << "number of corns: " << contours.size() << endl;
imshow("result Img", markers);
waitKey(0);
}
结果: