How do I track a blob using OpenCV and Python

牧云@^-^@ 提交于 2019-12-06 01:58:19

问题


I've gotten OpenCV working with Python and I can even detect a face through my webcam. What I really want to do though, is see movement and find the point in the middle of the blob of movement. The camshift sample is close to what I want, but I don't want to have to select which portion of the video to track. Bonus points for being able to predict the next frame.

Here's the code I have currently:

#!/usr/bin/env python

import cv

def is_rect_nonzero(r):
    (_,_,w,h) = r
    return (w > 0) and (h > 0)

class CamShiftDemo:

    def __init__(self):
        self.capture = cv.CaptureFromCAM(0)
        cv.NamedWindow( "CamShiftDemo", 1 )
        self.storage = cv.CreateMemStorage(0)
        self.cascade = cv.Load("/usr/local/share/opencv/haarcascades/haarcascade_mcs_upperbody.xml")
        self.last_rect = ((0, 0), (0, 0))

    def run(self):
        hist = cv.CreateHist([180], cv.CV_HIST_ARRAY, [(0,180)], 1 )
        backproject_mode = False
        i = 0
        while True:
            i = (i + 1) % 12

            frame = cv.QueryFrame( self.capture )

            if i == 0:
                found = cv.HaarDetectObjects(frame, self.cascade, self.storage, 1.2, 2, 0, (20, 20))
                for p in found:
                    # print p
                    self.last_rect = (p[0][0], p[0][1]), (p[0][2], p[0][3])
                    print self.last_rect

            cv.Rectangle( frame, self.last_rect[0], self.last_rect[1], cv.CV_RGB(255,0,0), 3, cv.CV_AA, 0 )
            cv.ShowImage( "CamShiftDemo", frame )

            c = cv.WaitKey(7) % 0x100
            if c == 27:
                break

if __name__=="__main__":
    demo = CamShiftDemo()
    demo.run()

回答1:


Found a solution at How do I track motion using OpenCV in Python?



来源:https://stackoverflow.com/questions/3374422/how-do-i-track-a-blob-using-opencv-and-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!