Opencv(C++)笔记--检测绘制轮廓

1--检测绘制轮廓

利用OpenCV检测轮廓的一般步骤:

        ①对原图像进行灰度化处理;

        ②对原图像进行二值化处理;

        ③检测并提取二值化图像的轮廓;

1-1--检测轮廓API

Opencv(C++)笔记--检测绘制轮廓_第1张图片

void cv::findContours(cv::InputArray image, cv::OutputArrayOfArrays contours, cv::OutputArray hierarchy, int mode, int method, cv::Point offset = cv::Point())

1-2--绘制轮廓API

Opencv(C++)笔记--检测绘制轮廓_第2张图片

void cv::drawContours(cv::InputOutputArray image, cv::InputArrayOfArrays contours, int contourIdx, const cv::Scalar &color, int thickness = 1, int lineType = 8, cv::InputArray hierarchy = noArray(), int maxLevel = 2147483647, cv::Point offset = cv::Point())

1-3--代码实例

# include 
# include 
# include 

cv::Mat src, dst;
int Threshold = 100;
int Thereshold_max = 255;

void Demo_Contours(int, void*){
    cv::Mat canny;
    std::vector> contours;
    std::vector hierachy;
    cv::Canny(src, canny, Threshold, Threshold *2, 3, false); // Canny二值化
    cv::findContours(canny, contours, hierachy, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE, cv::Point(0,0));

    dst.create(src.size(), CV_8UC3);
    cv::RNG rng(12345);
    for(size_t i = 0; i < contours.size(); i++){
        cv::Scalar color = cv::Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); // 利用随机数生成颜色
        cv::drawContours(dst, contours, i, color, 2, 8, hierachy, 0, cv::Point(0, 0));
    }
    cv::imshow("output", dst);
}

int main(int argc, char** argv){
    src = cv::imread("C:/Users/Liujinfu/Desktop/opencv_bilibili/test1.jpg"); 
    if (src.empty()){
        printf("could not load image..\n");
        return -1;
    }
    cv::imshow("input", src);
    cv::cvtColor(src, src, cv::COLOR_BGRA2GRAY); // 灰度化

    // 创建Trackbar
    cv::createTrackbar("Threshold", "input", &Threshold, Thereshold_max, Demo_Contours);
    Demo_Contours(0, 0);

    cv::waitKey(0);
    return 0;
}

Opencv(C++)笔记--检测绘制轮廓_第3张图片

你可能感兴趣的:(Opencv(C++)学习笔记,opencv,计算机视觉,人工智能)