opencv029-凸包

23 篇文章 0 订阅

概念介绍

l什么是凸包(Convex Hull)在一个多变形边缘或者内部任意两个点的连线都包含在多边形边界或者内部。

正式定义:

包含点集合S中所有点的最小凸多边形称为凸包

l检测算法

- Graham扫描法

概念介绍-Graham扫描算法

l首先选择Y方向最低的点作为起始点p0

lp0开始极坐标扫描,依次添加p1….pn(排序顺序是根据极坐标的角度大小,逆时针方向)

l对每个点pi来说,如果添加pi点到凸包中导致一个左转向(逆时针方法)则添加该点到凸包, 反之如果导致一个右转向(顺时针方向)删除该点从凸包中

lNo worry,我们只是需要了解,OpenCV已经实现了凸包发现算法和API提供我们使用。

API说明cv::convexHull

lconvexHull(

InputArray points,// 输入候选点,来自findContours

OutputArray hull,// 凸包

bool clockwise,// default true, 顺时针方向

bool returnPoints// true 表示返回点个数,如果第二个参数是  vector<Point>则自动忽略

代码演示

l首先把图像从RGB转为灰度

l然后再转为二值图像

l在通过发现轮廓得到候选点

l凸包API调用

l绘制显示。

#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;
void Threshold_Callback(int, void*);
const char * input_image = "input";
const char output_win[] = "output";
int main(int agrc, char** agrv) {
	Mat hsvbase, hsvtest1, hsvtest2;
	src = imread("C:/Users/liyangxian/Desktop/bjl/tubao.png");
	if (!src.data) {
		printf("no load..\n");
		return -1;
	}
	namedWindow(input_image, CV_WINDOW_AUTOSIZE);
	namedWindow(output_win, CV_WINDOW_NORMAL);
	imshow(input_image, src);
	cvtColor(src, src_gray, CV_BGR2GRAY);
	blur(src_gray, src_gray, Size(3, 3), Point(-1, -1), BORDER_DEFAULT);
	const char * trackbar_title = "Threshold:";
	createTrackbar(trackbar_title, 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_INV);
	findContours(bin_output, contours, hierachy, RETR_EXTERNAL, 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);
	RNG rng(12345);
	for (size_t k = 0; k < convexs.size(); k++) {
		Scalar color = (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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值