轮廓提取

 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
#include <opencv2/opencv.hpp>
#include <stdio.h>

using namespace std;
using namespace cv;


Mat img;

void changeThresh(int val,void* userdata){
    // 1. 定义结果矩阵
    Mat cannyImg;

    // 使用Canny算法获取图像的边缘信息
    Canny(img,cannyImg,50,val);

    // 调用api从canny图像上查找轮廓
    vector<vector<Point>> contours;
    vector<Vec4i> hierachy;

    findContours(cannyImg,contours,hierachy,RETR_EXTERNAL,CHAIN_APPROX_NONE);

    Mat dst = Mat::zeros(img.size(), img.type());
    drawContours(dst,contours,-1,Scalar(255,255,0),2,LINE_AA);


    // 绘制轮廓
    for(int i=0;i<contours.size();i++){
       vector<Point> c = contours[i];
       // 计算面积
       double area = contourArea(c);
       cout<<"面积为:"<<area<<endl;
       // 计算弧长
       double arc = arcLength(c,true);
       cout<<"弧长为:"<<endl;

       // 计算外切圆
       Point2f center;
       float radius;
       minEnclosingCircle(c,center,radius);
       cout<<"圆心坐标:"<<center<<"  半径:"<<radius;

       circle(dst,center,radius,Scalar(0,0,255),2,LINE_AA);
    }

    imshow("dst",dst);
    int i = *static_cast<int *>(userdata);
    cout<<val<<"======"<<(i)<<endl;

}

int main(){
    img = imread("../assets/shape.jpg", IMREAD_COLOR);

    imshow("src",img);

    int thresh=104;
    int userdata=100;

    cout<<userdata<<"=="<<&userdata<<endl;
    namedWindow("dst");
    createTrackbar("thresh","dst",&thresh,255,changeThresh,&userdata);
    changeThresh(104,&userdata);
//    imshow("dst",img);


    waitKey(0);
    destroyAllWindows();
    return 0;
}