OpenCV(Python)绘制视频,跟踪

时间:2017-05-03 05:32:29

标签: python opencv drawing

# libraries that will be needed
import numpy as np  # numpy
import cv2          # opencv
import imutils      # allows video editing
import random       
from imutils.object_detection import non_max_suppression
from imutils import paths
import imutils
import cv2

#default HOG
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())


# function to trak people
def tracker(cap):
    while True:
        ret, img = cap.read()

    # if video stopped playing, quit
    if ret == False:
        break

        # resize window
        img = imutils.resize(img, width = 400)
        # convert to graysclae and equalize
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        gray = cv2.equalizeHist(gray)

        # detect people
        rects, weights = hog.detectMultiScale(gray, winStride = (8, 8), padding = (8, 8), scale = 1.25)
        # store detected people in array
        rects = np.array([[x, y, x+w, y+h] for(x, y, w, h) in rects] )
        # find largest possible rectangel to avoid detection
        # of same person several times
        biggest = non_max_suppression(rects, probs = None, overlapThresh = 0.65)

        # draw largest rectangle
        for (xA, yA, xB, yB) in biggest:
            # create random color
            color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
            cv2.rectangle(img, (xA, yA), (xB, yB), color, 2)        

        # show image
        cv2.imshow('Image', img)

        k = cv2.waitKey(30) & 0xFF
        if k == 27:
            break
# run video
cap = cv2.VideoCapture('NYC.mp4')
tracker(cap)
# release frame and destroy windows
cap.release()
cv2.destroyAllWindows

我正尝试使用OpenCV一次跟踪多个人。一旦检测到一个人,我就会在它们周围画一个矩形。我在为每个人提供一个随机/不同颜色的盒子时遇到问题,同时在检测到一个人后保持相同的颜色盒。

目前,检测到某人并绘制了一个方框。在下一帧中,如果仍然检测到它们,则会绘制一个新的彩色框,但我想保持原始颜色。

同样开放的提示/技巧将改善我的代码和跟踪,因为我对此非常陌生。

2 个答案:

答案 0 :(得分:0)

如果你想为同一个人绘制相同的颜色框,你需要一种方式可以很自信地说出这是下一帧中的人。有很多方法可以做到这一点。 一种方法是你可以使用跟踪。尝试使用Camshift / meanshift跟踪(当然有许多跟踪算法,我不确定哪一个最适合你,因为我不知道你的数据集)。

检测到某人后,初始化一个跟踪器并为该人分配一个颜色框。如果人员不在图像中,则有一个系统从列表中删除该人。

希望这有帮助:)

答案 1 :(得分:0)

您的if ret == False:没有正确缩进以匹配while True:循环。当前代码:

def tracker(cap):
    while True:
        ret, img = cap.read()

    # if video stopped playing, quit
    if ret == False:
        break

        # resize window
        img = imutils.resize(img, width = 400)
        # convert to graysclae and equalize
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        gray = cv2.equalizeHist(gray)

固定缩进:

def tracker(cap):
    while True:
        ret, img = cap.read()

        # if video stopped playing, quit
        if ret == False:
            break

        # resize window
        img = imutils.resize(img, width = 400)
        # convert to graysclae and equalize
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        gray = cv2.equalizeHist(gray)