4. 图像计数

示例代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
    统计零件的数量
*/
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main(){
    // 图片路径
    string path = "/home/kaijun/Pictures/lingjian.png";
    //1. 读取图片
    Mat src = imread(path,IMREAD_COLOR);
    imshow("src",src);
    //2. 将图片转成灰度
    Mat gray;
    cvtColor(src,gray,COLOR_BGR2GRAY);

    // 将灰度图转成而制图,并且去掉背景
    Mat binary;
    threshold(gray,binary,0,255,THRESH_BINARY|THRESH_TRIANGLE);
    imshow("no background",binary);

    // 距离变换
    Mat dist;
    distanceTransform(binary,dist,DIST_L2,3);
    normalize(dist, dist, 0, 1.0, NORM_MINMAX);
    imshow("dist",dist);

    // 将距离变换的结果,通过阈值让图像粘连断开
    threshold(dist, dist, 0.5, 1.0, THRESH_BINARY);
    imshow("dist2",dist);

    // 统计图像的轮廓
    vector<vector<Vec2i>> contours;
    vector<Vec4i> hierarchy;

    cout<<dist.type()<<endl;
    dist.convertTo(dist,CV_8UC1);
    findContours(dist,contours,hierarchy,RETR_LIST,CHAIN_APPROX_NONE);

    cout<<contours.size()<<endl;

    // 绘制轮廓
    RNG rng(123456);
    Mat result(dist.size(),CV_8UC3);
    for (int i = 0; i < contours.size(); ++i) {
    drawContours(result,contours,i,Scalar(rng.uniform(0,255),rng.uniform(0,255),rng.uniform(0,255)),-1);
    }

    imshow("result",result);
    waitKey(0);
    return 0;
}