Opencv / python: motion detects strange threshold

Hi guys, so I am trying to make a motion detection program using my webcam, but I am getting these weird results at frame threshold difference:

When I'm moving: (it seems, I think, I think) enter image description here

When I'm not moving: enter image description here

What could it be? I have already run several programs which got exactly the same algorithm and the threshold works fine.

Here is my code:

import cv2
import random
import numpy as np

# Create windows to show the captured images
cv2.namedWindow("window_a", cv2.CV_WINDOW_AUTOSIZE) 
cv2.namedWindow("window_b", cv2.CV_WINDOW_AUTOSIZE)

# Structuring element
es = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9,4))
## Webcam Settings
capture = cv2.VideoCapture(0)

#dimensions
frameWidth = capture.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)
frameHeight = capture.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)

while True:
    # Capture a frame
    flag,frame = capture.read()

    current = cv2.blur(frame, (5,5))
    difference = cv2.absdiff(current, previous) #difference is taken of the current frame and the previous frame

    frame2 = cv2.cvtColor(difference, cv2.cv.CV_RGB2GRAY)
    retval,thresh = cv2.threshold(frame2, 10, 0xff, cv2.THRESH_OTSU)
    dilated1 = cv2.dilate(thresh, es)
    dilated2 = cv2.dilate(dilated1, es)
    dilated3 = cv2.dilate(dilated2, es)
    dilated4 = cv2.dilate(dilated3, es)

    cv2.imshow('window_a', dilated4)
    cv2.imshow('window_b', frame)

    previous = current

    key = cv2.waitKey(10) #20
    if key == 27: #exit on ESC
        cv2.destroyAllWindows()
        break

      

Thanks in advance!

+3


source to share


1 answer


The first thing you need is previous = cv2.blur(frame, (5,5))

to carry over the previous sample after capturing the frame before the while loop.

This will do the code you posted, but won't solve your problem.



I think the problem you are having is related to the type of threshold algorithm you are using. Try binary cv2.THRESH_BINARY

instead of Otsu. It seemed to me that this problem was solved.

0


source







All Articles