背景建模和光流估计是计算机视觉领域中两个重要的任务,它们通常用于视频分析和物 体跟踪。背景建模是从视频序列中提取出场景的静态背景信息的过程。在视频中,背景通常 是不变的元素,如墙壁、地面或天空。通过背景建模,我们可以检测到场景中的动态物体, 因为它们与背景不同。光流是描述图像序列中像素运动的矢量场的概念。光流估计旨在推断 连续帧之间的像素位移。这对于理解场景中的运动、跟踪物体以及分析视频中的动态变换非 常重要 以下是代码,和检测
import cv2 import numpy as np #使用帧插法的建模 def frameDiff(): cap=cv2.VideoCapture("BackGround/towStreetCar.mp4") es = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 4)) #上一帧 background=None while True: # 读取视频帧 ret, frame = cap.read() if background is None: background=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) background=cv2.GaussianBlur(background,(15,15),0) continue gray_frame=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) gray_frame=cv2.GaussianBlur(gray_frame,(15,15),0) diff=cv2.absdiff(background,gray_frame) diff = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)[1] thros = cv2.dilate(diff, es, iterations=2) cv2.imshow("fiff",thros) image, cnts, hierarchy = cv2.findContours(diff.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for c in cnts: if cv2.contourArea(c) < 1500: continue (x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) ret,thros =cv2.threshold(diff,25,255,cv2.THRESH_BINARY) # 显示视频帧 cv2.imshow('video', frame) cv2.imshow('diff', diff) background=gray_frame # 按下'q'键时退出循环 if cv2.waitKey(30) & 0xFF == ord('q'): break cv2.destroyAllWindows() cap.release() if __name__ == '__main__': frameDiff()标签:gray,frame,cv2,建模,估计,background,光流,diff From: https://blog.csdn.net/yzx991013/article/details/144593989