用opencv将物体框出

来源:互联网 发布:松下plc编程视频教程 编辑:程序博客网 时间:2024/05/21 08:53

经过国庆节的一天,终于把我的任务完成了,分享给大家看看。(第一次吐舌头


#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>

using namespace cv;
using namespace std;
RNG g_rng(12345);//产生随机值
int main()
{
Mat gray,blur_image,close_image,dst;

//【1】读取图像
Mat src = imread("1.jpg");
imshow("【原图】", src);

//【2】图像灰度化
cvtColor(src, gray, CV_BGR2GRAY);
/*imshow("【灰度图】", gray);*/

//【3】均值滤波
blur(gray, blur_image, Size(9, 9));
/*imshow("【均值滤波后的图】", blur_image);*/

//【4】图像二值化
Mat mid = blur_image.clone();
for (int i = 0; i < mid.rows; ++i)//可以根据自己的喜好使图像二值化
{
uchar *data = mid.ptr<uchar>(i);
for (int j = 0; j < mid.cols; ++j)
{
if (data[j]>90 && data[j] < 230)
data[j] = 255;
else
data[j] = 0;
}
}
/*threshold(blur_image, mid, 90, 230, CV_THRESH_BINARY);*/ //另一种二值图的方法(中间白,两边2黑)
/*imshow("【二值图】", mid);*/

//【5】闭运算
Mat element = getStructuringElement(MORPH_RECT, Size(15, 15));
morphologyEx(mid, close_image, MORPH_CLOSE, element);
//imshow("【运算后的图】", close_image);

//【6】查找轮廓
Mat outline_image = Mat::zeros(mid.rows, mid.cols, CV_8UC3);
vector<vector<Point>> contours;
vector<Vec4i> hierarcy;
findContours(close_image, contours, hierarcy, RETR_CCOMP, CHAIN_APPROX_SIMPLE);
for (int index = 0; index >= 0; index = hierarcy[index][0])
{
Scalar color = Scalar(g_rng.uniform(0, 255), g_rng.uniform(0, 255), g_rng.uniform(0, 255));
drawContours(outline_image, contours, index, color, NULL, 8, hierarcy);
}
//imshow("【轮廓图】", outline_image);


//【7】用最小的矩形框出物体
dst = src.clone();
for (int i = 0; i<contours.size(); i++)
{
//每个轮廓
vector<Point> points = contours[i];
//对给定的2D点集,寻找最小面积的包围矩形
RotatedRect box = minAreaRect(Mat(points));
Point2f vertex[4];
box.points(vertex);
cout << "第" << (i + 1) << "个矩形,其坐标为:" << vertex[0] << vertex[1] << vertex[2] << vertex[3] << endl;//输出矩形的4个点
//绘制出最小面积的包围矩形
line(dst, vertex[0], vertex[1], Scalar(g_rng.uniform(0, 255), g_rng.uniform(0, 255), g_rng.uniform(0, 255)), 3, CV_AA);//可以自己定义颜色,我比较喜欢随机,所以就长了点
line(dst, vertex[1], vertex[2], Scalar(g_rng.uniform(0, 255), g_rng.uniform(0, 255), g_rng.uniform(0, 255)), 3, CV_AA);
line(dst, vertex[2], vertex[3], Scalar(g_rng.uniform(0, 255), g_rng.uniform(0, 255), g_rng.uniform(0, 255)), 3, CV_AA);
line(dst, vertex[3], vertex[0], Scalar(g_rng.uniform(0, 255), g_rng.uniform(0, 255), g_rng.uniform(0, 255)), 3, CV_AA);
}
imshow("【绘制的最小面积矩形】", dst);

waitKey(0);
return 0;

}


过程都非常的清楚