OpenCV4入门151:背景分割

索引地址:系列索引

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
#include "opencv2/opencv.hpp"

using namespace std;
using namespace cv;

int main() {
VideoCapture cam(0);
if (!cam.isOpened())
return -1;

int history = 500;
double dist2Threshold = 400.0;
bool detectShadows = true;
Ptr<BackgroundSubtractorKNN> bgs =
createBackgroundSubtractorKNN(history, dist2Threshold, detectShadows);

while (true) {
Mat frame;
cam >> frame;
if (frame.empty())
break;

Mat fgMask;
bgs->apply(frame, fgMask);

medianBlur(fgMask, fgMask, 3);

Mat fg;
bitwise_and(frame, frame, fg, fgMask);

Mat bg;
bgs->getBackgroundImage(bg);

imshow("Video", frame);
imshow("Background", bg);
imshow("Foreground Mask", fgMask);
imshow("Foreground Image", fg);

int key = waitKey(10);
if (key == 27) // escape key
break;
}

cam.release();

return 0;
}