OpenCV-帧差法
通过帧差法可以获取到不同帧之间的差异:
#encoding:utf-8
import cv2
import numpy as np
from time import time
cap = cv2.VideoCapture("out.avi")
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fps = int(cap.get(cv2.CAP_PROP_FPS))
frameIds = np.linspace(0,total_frames-1,num=fps,dtype=np.int32)
frames = []
for fid in frameIds:
cap.set(cv2.CAP_PROP_POS_FRAMES,fid)
ret,frame = cap.read()
if ret:
frames.append(frame)
medianFrame = np.median(frames,axis=0).astype(np.uint8)
grayMedianFrame = cv2.cvtColor(medianFrame,cv2.COLOR_BGR2GRAY)
cap.set(cv2.CAP_PROP_POS_FRAMES,0)
while cap.isOpened():
ret,frame = cap.read()
if ret:
gray_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
d_frame = cv2.absdiff(gray_frame,grayMedianFrame)
d_frame = cv2.GaussianBlur(d_frame, (3,3), 5)
th,d_frame = cv2.threshold(d_frame,15,255,cv2.THRESH_BINARY)
cv2.imshow("Frame",frame)
cv2.imshow("Diff",d_frame)
key = cv2.waitKey(1000//fps)
if key & 0xFF == ord("q"):
break
else:
break
cap.release()
cv2.destroyAllWindows()
参考链接:
https://docs.opencv.org/4.9.0/d2/de8/group__core__array.html#ga6fef31bc8c4071cbc114a758a2b79c14
https://docs.opencv.org/4.9.0/d4/d15/group__videoio__flags__base.html#ggaeb8dd9c89c10a5c63c139bf7c4f5704da7c2fa550ba270713fca1405397b90ae0
https://www.cnblogs.com/leoych/p/12060317.html