OpenCV/Python: 运动检测奇怪的阈值化

3
我正在尝试使用我的网络摄像头制作一个运动检测程序,但在阈值化帧差时得到了奇怪的结果:
当我移动时:(似乎还好吧) ![enter image description here][1]
当我没有移动时: ![enter image description here][2]
这可能是什么原因呢?我已经运行了几个程序,这些程序确切地使用了相同的算法,阈值化也运行良好。
以下是我的代码:
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

感谢您的提前帮助! [1]: http://i.stack.imgur.com/hslOs.png [2]: http://i.stack.imgur.com/7fB95.png

我遇到了荧光灯的问题。稀释似乎解决了这些问题。你为什么使用膨胀调用? - tvandenbrande
1个回答

0

你需要的第一件事是在 while 循环之前使用 previous = cv2.blur(frame, (5,5)) 来初始化你的前一个样本。

这将使你发布的代码工作,但不会解决你的问题。

我认为你遇到的问题是由于你使用的阈值算法类型。尝试使用二进制的 cv2.THRESH_BINARY,而不是 Otsu 的算法。这对我来说似乎解决了问题。


谢谢!现在好多了。但是它还不是完全准确的,仍然有一些部分没有移动,并且仍然出现白色像素.. 有什么技巧可以使它比现在更准确吗?谢谢 - Cap.Alvez
嗯... 好像很难说,因为它对我来说似乎没有那样的表现。我的建议是关闭相机的自动调整功能。如果您的相机正在自动调整白平衡、对焦、亮度、曝光时间等,则可能会严重影响您的图像减法。 - derricw

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接