python代码:
import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
fgbg = cv.createBackgroundSubtractorMOG2(history=500, varThreshold=1000, detectShadows=False)
while True:
ret, frame = cap.read()
fgmask = fgbg.apply(frame)
background = fgbg.getBackgroundImage()
cv.imshow('input', frame)
cv.imshow('mask',fgmask)
cv.imshow('background', background)
k = cv.waitKey(10)&0xff
if k == 27:
break
cap.release()
cv.destroyAllWindows()
![90dfdfa10dea940c565ba1ece5c6826f.png](https://i-blog.csdnimg.cn/blog_migrate/89f80cf3d578c9bf861662d6d1f265d0.jpeg)
C++代码:
#include <opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
int main(int argc, char** argv) {
VideoCapture capture(0);
if (!capture.isOpened()) {
printf("could not open camera...n");
return -1;
}
namedWindow("input", WINDOW_AUTOSIZE);
namedWindow("mask", WINDOW_AUTOSIZE);
int fps = capture.get(CAP_PROP_FPS);
int width = capture.get(CAP_PROP_FRAME_WIDTH);
int height = capture.get(CAP_PROP_FRAME_HEIGHT);
int num_of_frames = capture.get(CAP_PROP_FRAME_COUNT);
printf("frame width: %d, frame height: %d, FPS : %d n", width, height, fps);
Ptr<BackgroundSubtractor> pMOG2 = createBackgroundSubtractorMOG2(500, 1000, false);
Mat frame, mask, back_img;
while (true) {
bool ret = capture.read(frame);
if (!ret) break;
pMOG2->apply(frame, mask);
pMOG2->getBackgroundImage(back_img);
imshow("input", frame);
imshow("mask", mask);
imshow("back ground image", back_img);
char c = waitKey(5);
if (c == 27) {
break;
}
}
waitKey(0);
return 0;
}
![4aff5891faf7f21e28326f6ff0ccadb5.png](https://i-blog.csdnimg.cn/blog_migrate/ecb32294fca5e649fa43b192739fb679.jpeg)
OpenCV学习笔记代码,欢迎follow:
MachineLP/OpenCV-github.com