fanfuhan OpenCV 教學079 ~ opencv-079-視頻分析(背景和前景的提取/抓取)
資料來源: https://fanfuhan.github.io/
https://fanfuhan.github.io/2019/04/24/opencv-079/
GITHUB:https://github.com/jash-git/fanfuhan_ML_OpenCV
視頻場景分析中最常用的技術之一就是通過背景消除來提取前景移動對象,得到前景的對象mask圖像,最常用的背景消除技術就是通過幀差相減,用前面一幀作為背景圖像,與當前幀進行相減,不過這種方法對光照與噪聲影響非常敏感,所有好的辦法是通過對前面一系列幀提取背景模型進行相減,OpenCV中實現的背景模型提取算法有兩種,一種是基於高斯混合模型GMM實現的背景提取,另外一種是基於最近鄰KNN實現的。
C++
#include#include using namespace std; using namespace cv; /* * 视频分析(背景和前景的提取) */ int main() { VideoCapture capture("../images/color_object.mp4"); if (!capture.isOpened()) { printf("could not open camera...\n"); return -1; } namedWindow("input", WINDOW_NORMAL); namedWindow("mask", WINDOW_NORMAL); namedWindow("background image", WINDOW_NORMAL); Mat frame, mask, back_img; Ptr pMOG2 = createBackgroundSubtractorMOG2(500, 1000, false); 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("background image", back_img); char c = waitKey(50); if (c == 27) { break; } } waitKey(0); return 0; waitKey(0); return 0; }
Python
import numpy as np import cv2 as cv cap = cv.VideoCapture('D:/images/video/color_object.mp4') 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()