2021-08-19opencv-凸包

该博客介绍了如何利用OpenCV库在C++中进行图像处理,特别是针对二值图像进行轮廓检测和凸包计算。首先,通过读取、转换和模糊处理图像来预处理,然后设置阈值并找到轮廓。使用findContours和convexHull函数获取轮廓及其凸包,并在原始图像上绘制。最后,展示了实时调整阈值以观察不同轮廓效果的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

凸包(在轮廓发现的基础上)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

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

using namespace cv;
using namespace std;

Mat src, dst;
int threshold_value = 50;
int threshold_max = 255;
const char* output = "output_image";
void convexHull_demo(int, void*);
RNG rng;
int main() {
	src = imread("D:/b.jpeg");
	if (src.empty()) {
		printf("could not load image");
		return -1;
	}
	namedWindow(output, WINDOW_AUTOSIZE);
	namedWindow("input", WINDOW_AUTOSIZE);
	imshow("input",src);

	cvtColor(src,src,COLOR_BGR2GRAY);
	blur(src,src,Size(3,3),Point(-1,-1),BORDER_DEFAULT);
	const char* threshold_bar = "threshold_bar";
	createTrackbar(threshold_bar,output,&threshold_value,threshold_max,convexHull_demo);
	convexHull_demo(0,0);

	waitKey();
	return 0;

}
void convexHull_demo(int ,void*) {
	Mat bin_output;
	vector<vector<Point>> contours;
	vector<Vec4i>hierachy;
	threshold(src, 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);

	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, Mat(), 0, Point(0, 0));

		imshow(output, dst);
		
	}
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值