使用OpenCV Python进行运动检测

时间:2017-04-09 06:22:36

标签: python opencv motion-detection

我需要检测此视频中的人物。我尝试过使用cv2.absdiff函数。但结果并不像预期的那样。 由于摄像机在拍摄视频时的动作,会出现许多误报。我该如何纠正? Link to video

camera = cv2.VideoCapture(args["video"])

firstFrame = None

while True:

    (grabbed, frame) = camera.read()
    text = ""

    # if the frame could not be grabbed, then we have reached the end
    # of the video
    if not grabbed:
        break

    # resize the frame, convert it to grayscale, and blur it
    frame = imutils.resize(frame, width=500)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (21, 21), 0)

    # if the first frame is None, initialize it
    if firstFrame is None:
        firstFrame = gray
        continue

    # compute the absolute difference between the current frame and
    # first frame
    frameDelta = cv2.absdiff(firstFrame, gray)
    thresh = cv2.threshold(frameDelta, 55, 255, cv2.THRESH_BINARY)[1]

    # dilate the thresholded image to fill in holes, then find contours
    # on thresholded image
    thresh = cv2.dilate(thresh, None, iterations=2)
    image = thresh.copy()
    image,cnts,hierarchy = cv2.findContours(image, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

    # loop over the contours
    for c in cnts:
        # if the contour is too small, ignore it
        #if cv2.contourArea(c) > args["max_area"] or cv2.contourArea < args["min_area"]:
        #   continue
        d = max(cnts, key = cv2.contourArea)
        # compute the bounding box for the contour, draw it on the frame,
        # and update the text
        (x, y, w, h) = cv2.boundingRect(d)
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        text = ""

    # show the frame and record if the user presses a key
    cv2.imshow("Security Feed", frame)

0 个答案:

没有答案