【OpenCV】轮廓周围绘制矩形框和圆形框
轮廓周围绘制矩形 -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在轮廓点上找到最小包含矩形和圆,旋转矩形与椭圆。
- 绘制它们
代码实现
#include<opencv2/opencv.hpp>
#include<iostream>
#include<math.h>
using namespace std;
using namespace cv;
Mat src, gray_src, drawImg;
int thresh_value = 100;
int thresh_max = 255;
const char* output_window = "output";
void Countours_callback(int, void*);
RNG rng(12345);
int main(int argc, char** grgv)
{
src = imread("1.jpg");
if (src.empty()) {
cout << "cannot load the image..." << endl;
return -1;
}
namedWindow("input", CV_WINDOW_AUTOSIZE);
imshow("input", src);
cvtColor(src, gray_src, CV_BGR2GRAY);
blur(gray_src, gray_src, Size(3, 3), Point(-1, -1), 4);
namedWindow(output_window, CV_WINDOW_AUTOSIZE);
createTrackbar("threshold_value", output_window, &thresh_value, thresh_max, Countours_callback);
Countours_callback(0, 0);
waitKey(0);
return 0;
}
void Countours_callback(int, void*) {
Mat binary_output;
threshold(gray_src, binary_output, thresh_value, thresh_max, THRESH_BINARY);
vector<vector<Point>>contours;
vector<Vec4i>hierachy;
findContours(binary_output, contours, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(-1, -1));
vector<vector<Point>> contours_ploy(contours.size());
vector<Rect> ploy_rects(contours.size());
vector<Point2f> ccs(contours.size());
vector<float> radius(contours.size());
vector<RotatedRect> minRects(contours.size());
vector<RotatedRect> myellipse(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], ccs[i], radius[i]);
if (contours_ploy[i].size() > 5) {
myellipse[i] = fitEllipse(contours_ploy[i]);
minRects[i] = minAreaRect(contours_ploy[i]);
}
}
// draw it
src.copyTo(drawImg);
Point2f pts[4];
for (size_t t = 0; t < contours.size(); t++) {
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
if (contours_ploy[t].size() > 5) {
ellipse(drawImg, myellipse[t], color, 1, 8);
minRects[t].points(pts);
for (int r = 0; r < 4; r++) {
line(drawImg, pts[r], pts[(r + 1) % 4], color, 1, 8);
}
}
}
imshow(output_window, drawImg);
return;
}
实验效果