python opencv从帧差异绘制轮廓

时间:2015-11-30 15:50:48

标签: python opencv

嗨,在下面的代码中,我正在制作帧差异,然后我想

找到从帧差异中出现的轮廓,并在它们出现时随时扫描它们

下面的代码可以很好地区分,但我的问题是轮廓,当它们出现时我无法绘制它们。当我运行它时会出现此错误消息:

  

cnt = contours [0]:索引错误列表索引超出范围

我在之前的例子中使用过cnt = contours [0]但是我不知道  这里有什么问题 。谢谢你的帮助

import cv2
import sys
import time
import numpy as np


BLUR_SIZE = 3
NOISE_CUTOFF = 12


cam = cv2.VideoCapture(0)

cam.set(3,640)
cam.set(4,480)

window_name = "delta view"
window_name_now = "now view"


frame_now = cam.read()[1]
frame_now = cam.read()[1]
frame_now = cv2.cvtColor(frame_now, cv2.COLOR_RGB2GRAY)
frame_now = cv2.blur(frame_now, (BLUR_SIZE, BLUR_SIZE))
frame_prior = frame_now

delta_count_last = 1
while True:
frame_delta = cv2.absdiff(frame_prior, frame_now)
frame_delta = cv2.threshold(frame_delta, NOISE_CUTOFF, 255, 3)[1]
delta_count = cv2.countNonZero(frame_delta)


cv2.normalize(frame_delta, frame_delta, 0, 255, cv2.NORM_MINMAX)
frame_delta = cv2.flip(frame_delta, 1)

kernel = np.ones((3,3),np.uint8)

opening = cv2.morphologyEx(frame_delta, cv2.MORPH_OPEN, kernel)
cont_img = opening.copy()
image,contours, hierarchy = cv2.findContours(cont_img, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnt=contours[0]
for cnt in contours:
 area = cv2.contourArea(cnt)
 if area < 2000 or area > 4000:
    continue

 if len(cnt) < 5:
    continue

ellipse = cv2.fitEllipse(cnt)
cv2.ellipse(roi, ellipse, (0,255,0), 2)
cv2.imshow('Contours', roi)

cv2.putText(frame_delta, "DELTA: %d" % (delta_count),
        (5, 15), cv2.FONT_HERSHEY_PLAIN, 0.8, (255, 255, 255))
cv2.imshow(window_name, opening)

#frame_delta = cv2.threshold(frame_delta, 92, 255, 0)[1]
dst = cv2.flip(frame_now, 1)
dst = cv2.addWeighted(dst,1.0, frame_delta,0.9,0)
cv2.imshow(window_name_now, dst)


if (delta_count_last == 0 and delta_count != 0):
    sys.stdout.write("MOVEMENT %f\n" % time.time())
    sys.stdout.flush()
elif delta_count_last != 0 and delta_count == 0:
    sys.stdout.write("STILL    %f\n" % time.time())
    sys.stdout.flush()
delta_count_last = delta_count

frame_prior = frame_now
frame_now = cam.read()[1]
frame_now = cv2.cvtColor(frame_now, cv2.COLOR_RGB2GRAY)
frame_now = cv2.blur(frame_now, (BLUR_SIZE, BLUR_SIZE))

key = cv2.waitKey(10)
if key == 0x1b or key == ord('q'):
    cv2.destroyWindow(window_name)
    break

0 个答案:

没有答案