3

I am trying to make a motion detect program using my webcam, but I'm getting this weird results when thresholding the difference of frames:

When Im moving: (seems okay I guess) ![enter image description here][1]

When Im not moving: ![enter image description here][2]

What can this be? I already ran a couple of programs that got exactly the same algorithm and the thresholding is doing fine..

Heres 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! [1]: https://i.stack.imgur.com/hslOs.png [2]: https://i.stack.imgur.com/7fB95.png

peterh
  • 11,875
  • 18
  • 85
  • 108
Cap.Alvez
  • 1,363
  • 3
  • 17
  • 19

1 Answers1

0

The first thing that you need is a previous = cv2.blur(frame, (5,5)) to prime your previous sample after a frame grab before your while loop.

This will make the code you posted work, but will not solve your problem.

I think the issue that you are having is due to the type of thresholding algorithm that you are using. Try a binary, cv2.THRESH_BINARY, instead of Otsu's. It seemed to solve the problem for me.

derricw
  • 6,757
  • 3
  • 30
  • 34
  • Thanks! It's much better now. But its not perfectly accurate there are still some parts that theres no movement and still appears white pixels in there.. Any tips to how to make this more accurate than it is? Thanks – Cap.Alvez Jan 25 '13 at 20:27
  • Hmm... well it is hard to say, because it doesnt seem to be doing that for me. My suggestion would be to turn off your camera's automatic adjustments. If your camera is auto-adjusting white balance, focus, brightness, exposure time, etc, it can really mess up your image subtraction. – derricw Jan 25 '13 at 20:45