OpenCv背景分离

BS背景分离技术

BS技术即通过把当前帧与背景模型相减得到前景掩码,再将前景掩码应用到当前帧上,最终形成的背景分离的视觉效果。如下演示:

OpenCv中的BS技术

OpenCv通过使用cv::BackgroundSubtractor类创建和更新背景类,示例如下:

# coding: utf-8
import cv2 as cv

def test(algo="MOG2"):
    """
    :param algo: MOG2 or KNN.
    """

    # 创建背景分离对象用于生成前景掩码
    if algo == "MOG2":
        back_sub = cv.createBackgroundSubtractorMOG2()
    else:
        back_sub = cv.createBackgroundSubtractorKNN()

    # 读取视频
    capture = cv.VideoCapture('car.mp4')
    while capture.isOpened():
        ret, frame = capture.read()
        if frame is None:
            break

        # 计算前景掩码和更新背景。
        frame = cv.flip(frame, 1)
        fg_mask = back_sub.apply(frame, learningRate=0.1)

        # 记录帧数
        cv.rectangle(frame, (10, 2), (100, 20), (255, 255, 255), -1)
        cv.putText(frame, str(capture.get(cv.CAP_PROP_POS_FRAMES)), (15, 15),
                   cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))

        # 输出当前帧和背景掩码
        cv.namedWindow('Frame', 0)
        cv.namedWindow('FG Mask', 0)
        cv.imshow("Frame", frame)
        cv.imshow("FG Mask", fg_mask)
        keyboard = cv.waitKey(30)
        if keyboard == 'q' or keyboard == 27:
            break


if __name__ == '__main__':
    test("MOG2")

posted @ 2022-06-17 22:47  东东咚咚东  阅读(230)  评论(0编辑  收藏  举报