#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;
}
多边形逼近C++与opencv实现
最新推荐文章于 2023-05-23 22:42:17 发布