opencv,关于物体检测

关于物体检测

环境:opencv 2.4.11+vs2013

参考:

http://www.cnblogs.com/tornadomeet/archive/2012/06/02/2531705.html

http://www.cnblogs.com/xinyuyuanm/archive/2013/04/29/3050750.html

 #include <string>
#include <iostream>
#include <stdio.h>
#include <fstream>
#include<math.h> #include <opencv2\opencv.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <opencv2\core\core.hpp> using namespace std;
using namespace cv; #define threshold_diff 20
int main()
{
Mat src1 = imread("图片1.png"), gray1;
cvtColor(src1, gray1, COLOR_BGR2GRAY);
Mat src2 = imread("图片2.png"), gray2;
cvtColor(src2, gray2, COLOR_BGR2GRAY);
//降噪
blur(gray1, gray1, Size(, ));
blur(gray2, gray2, Size(, )); //二值化
Mat gray_diff;
//CvMat *src1, *src2;
//cvAbsDiff(gray_src_y, gray_src_no, abs_src);
subtract(gray2, gray1, gray_diff);
for (int i = ; i < gray_diff.rows; i++)
{
for (int j = ; j < gray_diff.cols; j++)
{
if (abs(gray_diff.at<unsigned char>(i,j)) >= threshold_diff)
gray_diff.at<unsigned char>(i, j) = ;
else
gray_diff.at<unsigned char>(i, j) = ;
}
} //开运算(膨胀腐蚀算子)
Mat out;
Mat element = getStructuringElement(MORPH_RECT, Size(, ));
erode(gray_diff, out, element);
dilate(out, out, element); //查找轮廓
Mat dst = Mat::zeros(out.size(), CV_8UC3);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(out, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
int index = , largestComp;
double maxArea = ;
for (; index >= ; index = hierarchy[index][])
{
const vector<Point>& c = contours[index];
double area = fabs(contourArea(Mat(c)));
if (area >maxArea)
{
maxArea = area;
largestComp = index; }
}
Scalar color(, , );
drawContours(dst, contours, largestComp, color, CV_FILLED, , hierarchy); imshow("轮廓图", dst); imshow("原图", src1);
imshow("放入物品", src2);
imshow("图片差", gray_diff);
imshow("开运算", out); waitKey();
system("pause");
return ;
}

opencv,关于物体检测

opencv,关于物体检测

上一篇:shell中的cat和文件分界符(<


下一篇:
「kuangbin带你飞」专题十九 矩阵