多边形逼近C++与opencv实现

#include<opencv2/opencv.hpp>
#include<iostream>
#include <opencv2\imgproc\types_c.h>  // CV_BGR2GRAY
#include<vector>
using namespace std;
using namespace cv;

Mat src01, gray_src01, dst01;
int threshold_v = 170;
int threshold_max = 255;
void contours_callback(int, void*)
{
	//二值化
	Mat binary_out;
	threshold(gray_src01, binary_out, threshold_v, threshold_max, THRESH_BINARY);
	vector<vector<Point>> contours;
	vector<Vec4i> hierachy;
	findContours(binary_out, contours, hierachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
	imshow("输出图", binary_out);

	vector<vector<Point>> contours_poly(contours.size());
	vector<Rect> ploy_rects(contours.size());
	for (size_t i = 0;i < contours.size();i++)
	{
		//多边形轮廓
		approxPolyDP(contours[i], contours_poly[i], 3, true);
		//矩形包围框
		ploy_rects[i] = boundingRect(contours_poly[i]);
	}
	//绘图
	src01.copyTo(dst01);
	RNG rng(123);
	for (size_t t = 0;t < contours.size();t++)
	{
		Scalar color = Scalar(rng.uniform(0,255), rng.uniform(0, 255), rng.uniform(0, 255));
		rectangle(dst01,ploy_rects[t],color,2,8);
	}
	imshow("矩形框轮廓", dst01);
}
int main01()
{
	src01 = imread("C:\\Users\\dell\\Desktop\\stuff.jpg");
	namedWindow("原图", WINDOW_AUTOSIZE);
	namedWindow("输出图", WINDOW_AUTOSIZE);
	namedWindow("矩形框轮廓", WINDOW_AUTOSIZE);
	cvtColor(src01, gray_src01, CV_BGR2GRAY);
	blur(gray_src01, gray_src01, Size(3, 3), Point(-1, -1));
	imshow("原图", gray_src01);
	createTrackbar("阈值", "输出图", &threshold_v, threshold_max, contours_callback);
	contours_callback(0, 0);

	waitKey(0);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值