|
轮廓周围绘制矩形 -API
approxPolyDP(InputArray curve, OutputArray approxCurve, double epsilon, bool closed)
基于RDP算法实现,目的是减少多边形轮廓点数
cv::boundingRect(InputArray points)得到轮廓周围最小矩形左上交点坐标和右下角点坐标,绘制一个矩形
cv::minAreaRect(InputArray points)得到一个旋转的矩形,返回旋转矩形

轮廓周围绘制圆和椭圆-API
cv::minEnclosingCircle(InputArray points, //得到最小区域圆形
Point2f& center, // 圆心位置
float& radius)// 圆的半径
cv::fitEllipse(InputArray points)得到最小椭圆

处理步骤:
首先将图像变为二值图像
发现轮廓,找到图像轮廓
通过相关API在轮廓点上找到最小包含矩形和圆,旋转矩形与椭圆。
绘制它们。

[C++] 纯文本查看 复制代码 /*
注意:
处理流程
首先将图像变为二值图像
发现轮廓,找到图像轮廓
通过相关API在轮廓点上找到最小包含矩形和圆,旋转矩形与椭圆。
绘制它们。
*/
#include <opencv2/opencv.hpp>
#include <iostream>
#include<math.h>
using namespace std;
using namespace cv;
Mat src, dst, gray;
int threshold_val = 170;
int threshold_max = 255;
void threshold_call(int, void*);
int main(int argc, char** argv) {
src = imread("2222.jpg");
if (!src.data) {
printf("加载图片异常\n");
return -1;
}
namedWindow("input", CV_WINDOW_AUTOSIZE);
imshow("input", src);
//转灰度图
cvtColor(src, gray, CV_BGR2GRAY);
//均值模糊减低噪声
blur(gray, gray, Size(3, 3), Point(-1, -1), BORDER_DEFAULT);
//创建拖动条
createTrackbar("拖动条:", "input", &threshold_val, threshold_max, threshold_call);
threshold_call(0, 0);
waitKey(0);
return 0;
}
void threshold_call(int, void*) {
Mat binary_output;
vector<vector<Point>> contours;
vector <Vec4i> hierachy;
//阈值二值化处理
threshold(gray, binary_output, threshold_val, threshold_max, THRESH_BINARY);
//寻找边缘
findContours(binary_output, contours, hierachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(-1, -1));
vector<vector<Point>>contours_Ploy(contours.size());
vector<Rect>Ploy_rects(contours.size());
vector<Point2f>css(contours.size());
vector<float> radius(contours.size());
vector<RotatedRect>minRects(contours.size());
vector<RotatedRect>myellispe(contours.size());
for (size_t i = 0; i < contours.size(); i++)
{
//提取轮廓的多边形拟合曲线
approxPolyDP(Mat(contours[i]), contours_Ploy[i], 3, true);
//提取最小矩形坐标
Ploy_rects[i] = boundingRect(contours_Ploy[i]);
//提取最小圆
minEnclosingCircle(contours_Ploy[i], css[i], radius[i]);
if (contours_Ploy[i].size() > 5) {
//寻找点集拟合椭圆(得到最小椭圆)
myellispe[i] = fitEllipse(contours_Ploy[i]);
//寻找点集的最小区域边界斜矩形
minRects[i] = minAreaRect(contours_Ploy[i]);
}
}
//绘制------------开始
//拷贝图片
src.copyTo(dst);
Point2f pts[4];
for (size_t t = 0; t < contours.size(); t++)
{
//设置颜色
Scalar color = Scalar(255, 0, 0);
/*rectangle(dst, Ploy_rects[t], color, 2, 8);
circle(dst, css[t], radius[t], color, 2, 8);*/
if (contours_Ploy[t].size() > 5) {
//画圆
ellipse(dst, myellispe[t], color, 1, 8);
minRects[t].points(pts);
//画矩形
for (int r = 0; r < 4; r++)
{
//画线
line(dst, pts[r], pts[(r + 1) % 4], color, 1, 8);
}
}
}
imshow("output", dst);
return;
}
|
|