我正在使用背景减法,并且正在使用python进行此操作,但是当我使用代码时,它只是通过接缝为我提供了相机看到的黑白图像。据我所知,如果镜头前没有任何东西移动,那么所有东西都应该变黑,但这是我所得到的图像。
问题截图:

这是我正在使用的代码。
import numpy as np
import cv2
import time
cap = cv2.VideoCapture(0)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
fgbg = cv2.BackgroundSubtractorMOG()
while(1):
ret, frame = cap.read()
fgmask = fgbg.apply(frame)
fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
cv2.imshow('frame',fgmask)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
首先,您应该对灰度图像执行背景减法。基本上,您应该做的是首先将一个帧保存为参考,然后从后续帧中减去它。
您希望事先进行某种模糊处理,然后再进行扩散处理以减少噪声。
这是基本代数可以执行的最基本的背景减法运算。您需要一个减法和几个形态运算。
import numpy as np
import cv2
import time
cap = cv2.VideoCapture(0)
ret, first = cap.read()
# Save the first image as reference
first_gray = cv2.cvtColor(first, cv2.COLOR_BGR2GRAY)
first_gray = cv2.GaussianBlur(first_gray, (21, 21), 0)
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
# In each iteration, calculate absolute difference between current frame and reference frame
difference = cv2.absdiff(gray, first_gray)
# Apply thresholding to eliminate noise
thresh = cv2.threshold(difference, 25, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations=2)
cv2.imshow("thresh", thresh)
key = cv2.waitKey(1) & 0xFF
# if the `q` key is pressed, break from the lop
if key == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5475 次 |
| 最近记录: |