原理
最近在learn opencv上学习简单的图像处理的知识,也算是提前了解一下opencv的基本操作吧。
基本思想就是利用中值滤波,找到视频帧中的背景,然后用每一帧的图像减去背景即可得到背景中移动的物体了。
代码实现
代码中用到的视频地址
代码如下:
import numpy as np
import cv2
import imageio
# Open Video
cap = cv2.VideoCapture('video.mp4')
# Randomly select 25 frames
frameIds = cap.get(cv2.CAP_PROP_FRAME_COUNT) * np.random.uniform(size=25)
print(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# Store selected frames in an array
frames = []
for fid in frameIds:
cap.set(cv2.CAP_PROP_POS_FRAMES, fid)
ret, frame = cap.read()
if ret==True:
frames.append(frame)
# Calculate the median along the time axis
medianFrame = np.median(frames, axis=0).astype(dtype=np.uint8)
# Display median frame
cv2.imshow('frame', cv2.cvtColor(medianFrame,cv2.COLOR_RGB2GRAY))
# set the frame id as 0
cap.set(cv2.CAP_PROP_POS_FRAMES,0)
gif=[]
while(True):
try:
ret,frame=cap.read()
graymedianFrame=cv2.cvtColor(medianFrame,cv2.COLOR_RGB2GRAY)
frame=cv2.cvtColor(frame,cv2.COLOR_RGB2GRAY)
dframe=cv2.absdiff(frame,graymedianFrame)
th, dframe = cv2.threshold(dframe, 30, 255, cv2.THRESH_BINARY)
if ret==True:
cv2.imshow('video',dframe)
gif.append(dframe)
cv2.waitKey(20)
else:
break
except:
imageio.mimsave("demo.gif",gif,"GIF")
cap.release()
cv2.destroyAllWindows()
效果如下:
效果还是挺不错的。