Python Opencv的新功能:使用网络摄像头阈值处理/扩展的运动跟踪

时间:2013-01-24 18:27:31

标签: python opencv webcam tracking motion

嘿大家我非常喜欢编程和python-opencv一般,我已经为此寻找答案,但我找不到它。

我尝试使用我的网络摄像头进行动作追踪:

  • 取当前帧和前一帧的绝对差值
  • 将其转换为灰度并运行阈值滤镜,以便只有已更改的像素(即有移动的位置)才为白色。所有其他像素都是黑色。

但是当我尝试阈值并在帧的差异中应用扩张时,我收到错误:

t_minus_dilate = cv2.dilate(t_minus_thresh, es)
TypeError: <unknown> is not a numpy array

这意味着使用的帧不是一个numpy数组?

这是我的代码的一部分:

cv2.namedWindow("window_b", cv2.CV_WINDOW_AUTOSIZE)
# Structuring element
es = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9,4))

## Webcam Settings
capture = cv2.VideoCapture(0)

def diffImg(t0, t1, t2): #calculates the difference between frames
    d1 = cv2.absdiff(t2, t1)
    d2 = cv2.absdiff(t1, t0)
    return cv2.bitwise_and(d1, d2)

t_minus = cv2.cvtColor(capture.read()[1], cv2.COLOR_RGB2GRAY)
t_minus_thresh = cv2.threshold(t_minus, 0, 255, cv2.THRESH_OTSU)
t_minus_dilate = cv2.dilate(t_minus_thresh, es)

t = cv2.cvtColor(capture.read()[1], cv2.COLOR_RGB2GRAY)
t_thresh = cv2.threshold(t, 0, 255, cv2.THRESH_OTSU)
t_dilate = cv2.dilate(t_minus_thresh, es)

t_plus = cv2.cvtColor(capture.read()[1], cv2.COLOR_RGB2GRAY)
t_plus_thresh = cv2.threshold(t_plus, 0, 255, cv2.THRESH_OTSU)
t_plus_dilate = cv2.dilate(t_plus_thresh, es)


while True:

    diff = diffImg(t_minus_dilate, t_dilate, t_plus_dilate) #difference between the frames
    cv2.imshow('window_b',diff)

    t_minus_dilate = t_dilate
    t = diff
    t_plus_dilate = cv2.dilate(diff, es)

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

我不知道这是使用它的最好方法但是我会用这个代码制作一个游戏,目标是弹出落在屏幕上的气泡,如果气泡所在的位置(如果有的话)气泡弹出。

提前致谢

1 个答案:

答案 0 :(得分:3)

试试这个:

retvel, t_minus_thresh = cv2.threshold(t_minus, 0, 255, cv2.THRESH_OTSU)
t_minus_dilate = cv2.dilate(t_minus_thresh, es)

cv2.threshold返回two values,第二个是图像