opencv/python:运动检测阈值异常

3 投票
1 回答
2894 浏览
提问于 2025-04-17 13:41

我正在尝试用我的网络摄像头制作一个运动检测程序,但在对比帧的差异时,结果有点奇怪:

当我在移动时:(看起来还不错吧)

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

1 个回答

0

首先,你需要在进入循环之前,先用 previous = cv2.blur(frame, (5,5)) 来处理一下你之前的画面。

这样做可以让你发的代码正常运行,但并不能解决你遇到的问题。

我觉得你遇到的问题可能是因为你使用的阈值算法类型不对。试试用二值化的 cv2.THRESH_BINARY,而不是Otsu算法。对我来说,这样做似乎解决了问题。

撰写回答