码迷,mamicode.com
首页 > 其他好文 > 详细

opencv,关于物体检测

时间:2016-07-14 02:04:04      阅读:352      评论:0      收藏:0      [点我收藏+]

标签:

关于物体检测

环境: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

 

 1 #include <string>
 2 #include <iostream>
 3 #include <stdio.h>
 4 #include <fstream>
 5 #include<math.h>
 6 
 7 #include <opencv2\opencv.hpp>
 8 #include <opencv2\highgui\highgui.hpp>
 9 #include <opencv2\imgproc\imgproc.hpp>
10 #include <opencv2\core\core.hpp>
11 
12 using namespace std;
13 using namespace cv;
14 
15 #define threshold_diff 20
16 int main()
17 {
18     Mat src1 = imread("图片1.png"), gray1;
19     cvtColor(src1, gray1, COLOR_BGR2GRAY);
20     Mat src2 = imread("图片2.png"), gray2;
21     cvtColor(src2, gray2, COLOR_BGR2GRAY);
22     //降噪
23     blur(gray1, gray1, Size(3, 3));
24     blur(gray2, gray2, Size(3, 3));
25 
26     //二值化
27     Mat gray_diff;
28     //CvMat *src1, *src2;
29     //cvAbsDiff(gray_src_y, gray_src_no, abs_src);
30     subtract(gray2, gray1, gray_diff);
31     for (int i = 0; i < gray_diff.rows; i++)
32     {
33         for (int j = 0; j < gray_diff.cols; j++)
34         {
35             if (abs(gray_diff.at<unsigned char>(i,j)) >= threshold_diff)
36                 gray_diff.at<unsigned char>(i, j) = 255;
37             else
38                 gray_diff.at<unsigned char>(i, j) = 0;    
39         }
40     }
41 
42     //开运算(膨胀腐蚀算子)
43     Mat out;
44     Mat element = getStructuringElement(MORPH_RECT, Size(3, 3));
45     erode(gray_diff, out, element);
46     dilate(out, out, element);
47 
48     //查找轮廓
49     Mat dst = Mat::zeros(out.size(), CV_8UC3);
50     vector<vector<Point>> contours;
51     vector<Vec4i> hierarchy;
52     findContours(out, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
53     int index = 0, largestComp;
54     double maxArea = 0;
55     for (; index >= 0; index  = hierarchy[index][0])
56     {
57         const vector<Point>& c = contours[index];
58         double area = fabs(contourArea(Mat(c)));
59         if (area >maxArea)
60         {
61             maxArea = area;
62             largestComp = index;
63 
64         }
65     }
66     Scalar color(0, 255, 0);
67     drawContours(dst, contours, largestComp, color, CV_FILLED, 8, hierarchy);
68 
69     imshow("轮廓图", dst);
70 
71     imshow("原图", src1);
72     imshow("放入物品", src2);
73     imshow("图片差", gray_diff);
74     imshow("开运算", out);
75     
76     waitKey(0);
77     system("pause");
78     return 0;
79 }

 

技术分享

技术分享

 

opencv,关于物体检测

标签:

原文地址:http://www.cnblogs.com/beihaidao/p/5668220.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!