假设我有背景图像bg
和当前帧I
,我怎样才能获得前景蒙版fgmask
?
注意:使用标准方法fgmask = abs(bg-I) > th
不能给出准确的结果,发现很多噪音。
我知道 opencv 中的 MOG2 函数,但这个函数的问题是 AFAIK 它根据模型生成的自适应背景给出前景蒙版。有没有设置这个背景?
更新:
我已经找到了一种获取前景蒙版的方法,但我认为它对光线和阴影很敏感。
def getForegroundMask(frame, background, th):
# reduce the nois in the farme
frame = cv2.blur(frame, (5,5))
# get the absolute difference between the foreground and the background
fgmask= cv2.absdiff(frame, background)
# convert foreground mask to gray
fgmask = cv2.cvtColor(fgmask, cv2.COLOR_BGR2GRAY)
# apply threshold (th) on the foreground mask
_, fgmask = cv2.threshold(fgmask, th, 255, cv2.THRESH_BINARY)
# setting up a kernal for morphology
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
# apply morpholoygy on the foreground mask to get a better result
fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_CLOSE, kernel)
return fgmask