注:此教程是对贾志刚老师的opencv课程学习的一个记录,在此表示对贾老师的感谢.
需求: 拍照统计玉米粒的数目
实现方法: 通过二值分割+形态学处理+距离变换+连通区域计算
代码:
#include
#include
#include
using namespace cv;
using namespace std;
int main(int argc, char **argv) {
Mat gray_src, binary, dst;
Mat src = imread("/home/fuhong/code/cpp/opencv_learning/src/small_case/imgs/case4.png");
if (src.empty()) {
printf("could not load image...\n");
return -1;
}
namedWindow("input image", CV_WINDOW_AUTOSIZE);
imshow("input image", src);
cvtColor(src, gray_src, COLOR_BGR2GRAY);
threshold(gray_src, binary, 0, 255, THRESH_BINARY | THRESH_TRIANGLE);
imshow("binary image", binary);
Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
dilate(binary, binary, kernel, Point(-1, -1), 1);
imshow("dilate image", binary);
Mat dist;
bitwise_not(binary, binary); //取反
distanceTransform(binary, dist, CV_DIST_L2, 0);
normalize(dist, dist, 0, 1.0, NORM_MINMAX);
imshow("dist image", dist);
Mat dist_8u;
dist.convertTo(dist_8u, CV_8U);
adaptiveThreshold(dist_8u, dist_8u, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 85, 0.0);
kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
dilate(dist_8u, dist_8u, kernel, Point(-1, -1), 2);
imshow("dist-binary", 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 (size_t t = 0; t < contours.size(); t++) {
drawContours(markers, contours, static_cast<int>(t),
Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)),
-1, 8, Mat());
}
printf("number of corns : %d", contours.size());
imshow("Final result", markers);
waitKey(0);
return 0;
}