[英]opencv background subtraction
我正在使用背景減法,我正在使用 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()
我究竟做錯了什么?
首先,您應該對灰度圖像執行背景減法。 你基本上應該做的是首先保存一個幀作為參考,然后從后續幀中減去它。
你想事先應用某種模糊,然后進行膨脹操作以減少噪音。
這是您可以使用基本代數進行的最基本的背景減法運算。 你需要的是一個減法和幾個形態學操作。
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()
相機沒有正確捕獲第一幀。 它只是捕獲了一個黑色圖像。 為了解決這個問題,我丟棄了第一幀,添加了一個睡眠,然后重新捕獲。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.