029-Opencv笔记-凸包

凸包

什么是凸包(Convex Hull),在一个多变形边缘或者内部任意两个点的连线都包含在多边形边界或者内部。
正式定义:包含点集合S中所有点的最小凸多边形称为凸包

Graham扫描算法

首先选择Y方向最低的点作为起始点p0,从p0开始极坐标扫描,依次添加p1….pn(排序顺序是根据极坐标的角度大小,逆时针方向)
对每个点pi来说,如果添加pi点到凸包中导致一个左转向(逆时针方法)则添加该点到凸包, 反之如果导致一个右转向(顺时针方向)删除该点从凸包中

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

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

using namespace std;
using namespace cv;
Mat src, src_gray, dst;
int threshold_value = 100;
int threshold_max = 255;
const char* output_win = "convex hull demo";
void Threshold_Callback(int, void*);
RNG rng(12345);

int main(int argc, char** argv) {
    src = imread("D:/girl.jpg");
    //src = imread("D:/cir.png");
    if (!src.data) {
        printf("could not load image...\n");
        return -1;
    }
    const char* input_win = "input image";
    namedWindow(input_win, CV_WINDOW_AUTOSIZE);
    namedWindow(output_win, CV_WINDOW_NORMAL);
    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);
    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, 8, hierachy, 0, Point(0, 0));
        drawContours(dst, convexs, k, color, 2, 8, empty, 0, Point(0, 0));
    }
    imshow(output_win, dst);

    return;
}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • nav寻路一般包含两部分,首先是使用工具根据地图信息生成寻路用的nav mesh,接下来就是在游戏中根据生成的na...
    _ArayA_阅读 2,356评论 0 1
  • 1 、凸包的理解 在一个多变形边缘或者内部任意两个点的连线都包含在多边形边界或者内部。正式定义:包含点集合S中所有...
    刘玉春_164c阅读 815评论 0 0
  • 凸包(Convex Hull)是一个计算几何(图形学)中的概念。在一个实数向量空间中,对于给定集合X,所有包含X的...
    其实我很菜啊阅读 3,530评论 0 0
  • 1 什么是叉乘 a×b=c 其中|c|=|a||b|·sinθ c的方向遵守右手定则二维向量的叉乘 ( ...
    氮化镓加砷阅读 9,184评论 1 3
  • 1.概念 凸包(Convex Hull)是一个计算几何(图形学)中的概念。用不严谨的话来讲,给定二维平面上的点集,...
    三三de酒阅读 4,115评论 0 1

友情链接更多精彩内容