-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
107 lines (85 loc) · 2.45 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <iostream>
#include <string>
#include <vector>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
const string videoPath = "roadcars.avi";
const string backgroundPath = "background.jpg";
int main(void)
{
// ��ȡ��Ƶ��
VideoCapture video(videoPath);
if (video.isOpened() == false)
{
cout << "error: cannot load video..." << endl;
exit(-1);
}
// ��ȡÿ֡�ijߴ�
int width = video.get(CAP_PROP_FRAME_WIDTH);// 320
int height = video.get(CAP_PROP_FRAME_HEIGHT);// 176
// ��ȡ����ͼ
Mat background = imread(backgroundPath, IMREAD_GRAYSCALE);
if (background.empty())
{
cout << "error: cannot load background..." << endl;
exit(-2);
}
// ��֡����
Mat frame, grayFrame;
Mat diffImg, blurDiffImg, binaryImg, cleanBinary;
Mat structElement = getStructuringElement(MORPH_RECT, Size(5, 5));
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
Rect outline;
bool flag1[5] = { false, false, false, false, false };
bool flag2[5] = { false, false, false, false, false };
int lim = 250;
int count = 0;
vector<Mat> channelImgs;
vector<Mat> resImgs;
Mat resImg, dilated;
char info[10] = { '0' };
for (;;)
{
video >> frame;
if (frame.empty())
break;
cvtColor(frame, grayFrame, COLOR_BGR2GRAY);
absdiff(grayFrame, background, diffImg);
diffImg *= 2;
blur(diffImg, blurDiffImg, Size(7, 7));
threshold(blurDiffImg, binaryImg, 30, 255, THRESH_BINARY);
morphologyEx(binaryImg, cleanBinary, MORPH_OPEN, structElement, Point(-1, -1), 1);
findContours(cleanBinary, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_NONE);
for (int i = 0; i < contours.size(); i++)
{
outline = boundingRect(contours[i]);
if (outline.area() > 1000 || outline.br().x > 260)
{
rectangle(frame, outline, Scalar(0, 0, 255), 1);
if (outline.br().x > lim)// �ղ���
flag1[i] = true;
if (flag1[i] == true && outline.br().x > lim && outline.tl().x < lim)// ��������
{
flag2[i] = true;
}
if (flag1[i] == true && flag2[i] == true && outline.tl().x > lim)// ��ȥ��
{
flag1[i] = false;
flag2[i] = false;
count++;
//cout << count << endl;
}
}
}
sprintf_s(info, "car:%d", count);
putText(frame, info, Point(200, 30), FONT_HERSHEY_SIMPLEX, 1.2, Scalar(0, 255, 0), 1);
imshow("��", frame);
if (waitKey(100) == 27)
break;
}
video.release();
destroyAllWindows();
return 0;
}