我是OpenCV的新手并决定学习它,但是编写一个小程序来检测动作并在对象上绘制一个边界框。
我从一个相当简单的方法开始,它简单地计算了两个帧之间的差异,找到了轮廓并在对象周围绘制了一个简单的矩形。这有一段时间了,但它无法在弹出多个对象时自动跟踪它们。我必须手动更改其参数才能跟踪 n 对象数量。
所以我决定改变我的方法,而是使用BackgroundSubtractorMOG
。这种方法对我想要完成的工作更有利,但我目前唯一的问题是如何在应用BackgroundSubtractorMOG
后绘制检测到的对象的轮廓。我不再需要矩形了,而是希望它围绕物体的边界绘制。
import sys
import cv2
def getImageDifference(first, second):
return cv2.absdiff(first, second)
def drawRectangle(contour, frame):
(x, y, w, h) = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
previousFrame = None
backgroundSubtractor = None
camera = cv2.VideoCapture(0)
backgroundSubtractor = cv2.BackgroundSubtractorMOG()
while True:
grabbed, frame = camera.read()
if not grabbed:
break
fgMask = backgroundSubtractor.apply(frame, learningRate = 1.0/10)
output = cv2.GaussianBlur(fgMask, (21, 21), 0)
if previousFrame is None:
previousFrame = fgMask
continue
frameDelta = getImageDifference(previousFrame, output)
maskRGB = cv2.cvtColor(fgMask,cv2.COLOR_GRAY2BGR)
frameDela = maskRGB
# frameDelta = cv2.cvtColor(fgMask, cv2.COLOR_BGR2GRAY)
threshold = cv2.threshold(fgMask, 21, 255, cv2.THRESH_BINARY)[1]
threshold = cv2.dilate(threshold, None, iterations = 2)
contours, hierarchy = cv2.findContours(threshold.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
sortedContours = sorted(contours, key = cv2.contourArea, reverse = True)[:2] #this will track two objects simultaneously. If I want more, I'd have to come and change this value to whatever I want
for contour in sortedContours:
drawRectangle(contour, frame)
previousFrame = output
draw = frame & maskRGB
cv2.imshow('Main',frame)
cv2.imshow('Background Subtraction', fgMask)
cv2.imshow('Background Subtraction with color', draw)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
camera.release()
cv2.destroyAllWindows()