相关知识:
相关程序
#include "stdafx.h"
//本节讲述 图像处理之 直方图比较;
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace std;
using namespace cv;
void contours_Callback(int, void*);
Mat src, test1, test2, dst ,gray_src, temp;
char input_title[] = "原图";
char output_title[] = "结果图";
int match_method = CV_TM_SQDIFF;
int max_track = 5;
int threshold_value = 50;
int max_threshold = 255;
int main(int argc, char**argv)
{
//src = imread("C:/Users/Rubison.DELL/Desktop\\杂物/壁纸/热气球2.png"); //待检测图
src = imread("C:/Users/Rubison.DELL/Desktop\\杂物/壁纸/小白2.jpg");
if (src.empty())
{
printf("could not load image...\r\n");
return -1;
}
namedWindow(input_title, CV_WINDOW_AUTOSIZE);
namedWindow(output_title, CV_WINDOW_AUTOSIZE);
imshow(input_title, src);
cvtColor(src, gray_src, CV_BGR2GRAY);
blur(gray_src, gray_src, Size(3, 3));
createTrackbar("Threshold Value", output_title, &threshold_value, max_threshold, contours_Callback);
contours_Callback(0, 0);
waitKey(0);
destroyAllWindows();
return 0;
}
void contours_Callback(int, void*)
{
//对图像进行二值化,控制阈值
Mat binary_output;
vector<vector<Point> > contours;//用于存放检测到的轮廓,数据类型为vector<vector>,每个轮廓中存放着属于该轮廓的像素坐标
vector<Vec4i> hierarchy; //用于存放各个轮廓之间的结构信息,数据类型为vector
threshold(gray_src, binary_output, threshold_value, max_threshold, THRESH_BINARY);
imshow("轮廓图", binary_output);
findContours(binary_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(-1, 1));
//
vector<vector<Point>> contours_poly(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 = 1; i < contours.size(); i++)
{
approxPolyDP(Mat(contours[i]), contours_poly[i], 3, true); // //减少每个轮廓的点数
ploy_rects[i] = boundingRect(Mat(contours_poly[i])); //得到包围轮廓最小矩形的左上角点坐标和右下角点坐标,绘制一个矩形
minEnclosingCircle(contours_poly[i], ccs[i], radius[i]); // 得到一个旋转的矩形,返回旋转矩形
if (contours_poly[i].size() > 5) //!!注意 该类型API要求点数必须大于5
{
myellipse[i] = fitEllipse(contours_poly[i]); //获取椭圆的二维点集
minRects[i] = minAreaRect(contours_poly[i]); //带有偏转角度的矩形框
}
}
//绘制
//dst = Mat::zeros(src.size(), CV_8UC3);
//Mat dst = Mat::zeros(src.size(), src.type());
RNG rng(12345);
src.copyTo(dst);
Point2f pts[4]; //Point2f表示Point类的两个数据x,y为float类型;
for (size_t j = 0; j < contours.size(); j++)
{
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
//Scalar color = Scalar(0, 0, 255);
rectangle(dst, ploy_rects[j], color,2,8 );
circle(dst, ccs[j], radius[j],color,2,8);
ellipse(dst, myellipse[j],color,2,8);
minRects[j].points(pts);
for (int k = 0; k < 4; k++)
{
line(dst, pts[k], pts[(k + 1) % 4],color,2,8 );
}
}
imshow(output_title, dst);
}
运行结果
备注:
1.椭圆拟合API:RotatedRect fitEllipse(InputArray points)
介绍:椭圆
2.最小包围矩形-minAreaRect函数(可偏转角度)VS boundingRect(垂直边界矩阵):两种矩阵的区别
最小矩阵
3.待定