此篇主要为临时记录代码后续编写过程慢慢补上
图片内容对象计数
原图片
图形计数
#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("data/corn.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, DIST_L2, 3);
normalize(dist, dist, 0, 1.0, NORM_MINMAX); //范围在0~1之间
imshow("distance", dist);
//形态学处理
Mat MorphImg;
dist.convertTo(MorphImg, 8U);
// threshold(MorphImg, MorphImg, 0.99, 255, THRESH_BINARY); //上面像素值在0~1之间
adaptiveThreshold(MorphImg, MorphImg, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 85, 0);
kernel = getStructuringElement(MORPH_RECT, Size(11, 11), Point(-1, -1));
// morphologyEx(MorphImg, MorphImg, MORPH_OPEN, kernel); //开操作
dilate(MorphImg, MorphImg, kernel, Point(-1, -1), 1);
imshow("t-distance", MorphImg);
//找到种子的轮廓区域
vector<vector<Point>> contours;
findContours(MorphImg, contours, 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);
}