0
点赞
收藏
分享

微信扫一扫

27 OpenCV 凸包

文章目录

概念

Graham扫描算法

convexHull 凸包函数

convexHull(
InputArray points,// 输入候选点,来自findContours
OutputArray hull,// 凸包
bool clockwise,// default true, 顺时针方向
bool returnPoints)// true 表示返回点个数,如果第二个参数是vector<Point>则自动忽略

示例

#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>

using namespace std;
using namespace cv;

Mat src, src_gray, dst; // 定义原始图像、灰度图像和结果图像
int threshold_value = 100; // 初始阈值设为100
int threshold_max = 255; // 最大阈值为255
const char* output_win = "convex hull demo"; // 定义输出窗口名称
RNG rng(12345); // 随机数生成器

// 回调函数声明
void Threshold_Callback(int, void*);

int main(int argc, char** argv) {
    src = imread("D:/vcprojects/images/hand.png"); // 读取图像
    if (!src.data) {
        printf("could not load image...\n");
        return -1;
    }
    
    const char* input_win = "input image";
    namedWindow(input_win); // 创建输入图像窗口
    namedWindow(output_win); // 创建输出图像窗口
    
    const char* trackbar_label = "Threshold : "; // 创建滑动条标题

    cvtColor(src, src_gray, CV_BGR2GRAY); // 将彩色图像转换为灰度图像
    blur(src_gray, src_gray, Size(3, 3), Point(-1, -1), BORDER_DEFAULT); // 对灰度图像进行模糊处理
    imshow(input_win, src_gray); // 在输入窗口中显示灰度图像

    createTrackbar(trackbar_label, output_win, &threshold_value, threshold_max, Threshold_Callback); // 创建阈值滑动条
    Threshold_Callback(0, 0); // 初始化回调函数

    waitKey(0); // 等待按键
    return 0;
}

void Threshold_Callback(int, void*) {
    Mat bin_output; // 二值化输出图像
    vector<vector<Point>> contours; // 存储轮廓点集
    vector<Vec4i> hierachy; // 轮廓层级关系
    
    threshold(src_gray, bin_output, threshold_value, threshold_max, THRESH_BINARY); // 对灰度图像进行阈值处理
    findContours(bin_output, contours, hierachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0)); // 查找图像中的轮廓

    vector<vector<Point>> convexs(contours.size()); // 存储凸包结果
    for (size_t i = 0; i < contours.size(); i++) {
        convexHull(contours[i], convexs[i], false, true); // 计算每个轮廓的凸包
    }

    dst = Mat::zeros(src.size(), CV_8UC3); // 创建与原始图像相同大小的空白图像
    vector<Vec4i> empty(0); // 空Vec4i用于绘制凸包

    for (size_t k = 0; k < contours.size(); k++) {
        Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); // 随机颜色
        drawContours(dst, contours, k, color, 2, LINE_8, hierachy, 0, Point(0, 0)); // 绘制轮廓
        drawContours(dst, convexs, k, color, 2, LINE_8, empty, 0, Point(0, 0)); // 绘制凸包
    }

    imshow(output_win, dst); // 在输出窗口中显示结果图像

    return;
}

在这里插入图片描述

举报

相关推荐

0 条评论