美文网首页
opencv寻找图像轮廓

opencv寻找图像轮廓

作者: 一路向后 | 来源:发表于2021-12-21 22:43 被阅读0次

1.源码实现

#include <cstdio>
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

using namespace std;
using namespace cv;

void thresh_callback(Mat &src_gray, const int thresh)
{
    Mat canny_output;
    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy;
    RNG rng(12345);

    //用Canny算子检测边缘
    Canny(src_gray, canny_output, thresh, thresh*2, 3);

    //寻找轮廓
    findContours(canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));

    //绘出轮廓
    Mat drawing = Mat::zeros(canny_output.size(), CV_8UC3);

    for(int i = 0; i< contours.size(); i++)
    {
        Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255));

        drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());
    }

    //保存结果
    imwrite("Contours.jpg", drawing);
}

int main()
{
    //加载源图像
    Mat src = imread("7.jpeg", 1);
    Mat src_gray;

    //转成灰度并模糊化降噪
    cvtColor(src, src_gray, CV_BGR2GRAY);
    blur(src_gray, src_gray, Size(3,3));

    thresh_callback(src_gray, 65);

    return 0;
}

2.编译源码

$ g++ -o test test.cpp -std=c++11 -I/usr/local/include/opencv4 -L/usr/local/lib -lopencv_core -lopencv_highgui -lopencv_imgproc -lopencv_ml -Wl,-rpath=/usr/local/lib

3.运行及其结果

7.jpeg
Contours.jpg

相关文章

网友评论

      本文标题:opencv寻找图像轮廓

      本文链接:https://www.haomeiwen.com/subject/neyfqrtx.html