#include <QCoreApplication>
#include "opencv2/opencv.hpp"
using namespace cv;
using namespace std;
//对象计数
int main()
{
src=imread("../image/13.png");
if(src.empty())
{
printf("could not load image ...");
return ;
}
imshow("src",src);
cvtColor(src,gray,CV_BGR2GRAY);
imshow("gray",gray);
Mat binary;
//二值化
threshold(gray,binary,0,255,THRESH_BINARY|THRESH_TRIANGLE);
imshow("output",binary);
//形态学操作
Mat kernel=getStructuringElement(MORPH_RECT,Size(3,3),Point(-1,-1));
//腐蚀操作
dilate(binary,binary,kernel,Point(-1,-1),1);
imshow("output1",binary);
// 距离变换
Mat dist;
bitwise_not(binary,binary);
//距离变换函数
distanceTransform(binary,dist,CV_DIST_L2,3);
//归一化操作
normalize(dist,dist,0,1.0,NORM_MINMAX);
imshow("output2",dist);
Mat dst;
// threshold(dist,dst,0.6,1.0,THRESH_BINARY);
//阈值化二值分割
Mat dist_8u;
dist.convertTo(dist_8u,CV_8U);
adaptiveThreshold(dist_8u,dist_8u,255,ADAPTIVE_THRESH_GAUSSIAN_C,THRESH_BINARY,85,0.0);
dilate(dist_8u,dist_8u,kernel,Point(-1,-1),2);
// normalize(dist_8u,dist_8u,0,1.0,NORM_MINMAX);
imshow("output3",dist_8u);
//连通区域技术
vector<vector<Point>> contours;
findContours(dist_8u,contours,CV_RETR_EXTERNAL,CHAIN_APPROX_SIMPLE);
//draw result
Mat markers=Mat::zeros(src.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());
Rect rect=boundingRect(contours[i]);
string str=to_string(i+1);
double area=contourArea(contours[i]);
printf("%d号玉米的面积是%2f\n",i+1,area);
putText(markers,str,Point(rect.x,rect.y),CV_FONT_NORMAL,0.5,Scalar(0,0,255),1,8,0);
}
printf("玉米有%d粒\n",contours.size());
imshow("markers",markers);
waitKey(0);
return 0;
}