opencv python中的运动跟踪

时间:2018-01-04 04:08:45

标签: python opencv motion-detection video-tracking

所以我一直试图制作一个动作跟踪器来跟踪在视频中移动的狗(自上而下记录)检索显示狗的裁剪视频并忽略其余的背景。

我首先尝试使用opencv 3中的可用算法进行对象跟踪(BOOSTING,MIL,KCF,TLD,MEDIANFLOW,GOTURN(返回错误,无法解决))this link我甚至通过减去第一帧来尝试运动跟踪的基本算法,但它们都没有给出好的结果。 Link

我更喜欢一个带有预设矩形框的代码,一旦检测到它就围绕着运动区域。像video

这样的东西

我对OPENCV不太熟悉,但我认为单一动作跟踪不应该是一个问题,因为已经完成了很多工作。我应该考虑其他库/ API还是有更好的代码/教程我可以遵循以完成这项工作?我的观点是稍后将其用于神经网络(这就是我尝试使用python / opencv解决它的原因)

感谢您提供任何帮助/建议

修改

我删除了以前的代码,以使帖子更清晰。

另外,根据我得到的反馈和进一步的研究,我能够修改一些代码,使其接近我想要的结果。但是,我仍然有一个恼人的跟踪问题。看起来第一帧影响了跟踪的其余部分,因为即使在狗移动之后,它仍然会检测到它的第一个位置。我尝试使用标志将跟踪限制为仅1个动作,但检测结果搞砸了。这是显示结果的代码和图片:

jimport imutils
import time
import cv2

previousFrame = None

def searchForMovement(cnts, frame, min_area):

    text = "Undetected"

    flag = 0

    for c in cnts:
        # if the contour is too small, ignore it
        if cv2.contourArea(c) < min_area:
            continue

        #Use the flag to prevent the detection of other motions in the video
        if flag == 0:
            (x, y, w, h) = cv2.boundingRect(c)

            #print("x y w h")
            #print(x,y,w,h) 
            cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
            text = "Detected"
            flag = 1

    return frame, text

def trackMotion(ret,frame, gaussian_kernel, sensitivity_value, min_area):


    if ret:

        # Convert to grayscale and blur it for better frame difference
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        gray = cv2.GaussianBlur(gray, (gaussian_kernel, gaussian_kernel), 0)



        global previousFrame

        if previousFrame is None:
            previousFrame = gray
            return frame, "Uninitialized", frame, frame



        frameDiff = cv2.absdiff(previousFrame, gray)
        thresh = cv2.threshold(frameDiff, sensitivity_value, 255, cv2.THRESH_BINARY)[1]

        thresh = cv2.dilate(thresh, None, iterations=2)
        _, cnts, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        frame, text = searchForMovement(cnts, frame, min_area)
        #previousFrame = gray

    return frame, text, thresh, frameDiff




if __name__ == '__main__':

    video = "Track.avi"
    video0 = "Track.mp4"
    video1= "Ntest1.avi"
    video2= "Ntest2.avi"

    camera = cv2.VideoCapture(video1)
    time.sleep(0.25)
    min_area = 5000 #int(sys.argv[1])

    cv2.namedWindow("Security Camera Feed")


    while camera.isOpened():

        gaussian_kernel = 27
        sensitivity_value = 5
        min_area = 2500

        ret, frame = camera.read()

        #Check if the next camera read is not null
        if ret:
            frame, text, thresh, frameDiff = trackMotion(ret,frame, gaussian_kernel, sensitivity_value, min_area)

        else:
            print("Video Finished")
            break


        cv2.namedWindow('Thresh',cv2.WINDOW_NORMAL)
        cv2.namedWindow('Frame Difference',cv2.WINDOW_NORMAL)
        cv2.namedWindow('Security Camera Feed',cv2.WINDOW_NORMAL)

        cv2.resizeWindow('Thresh', 800,600)
        cv2.resizeWindow('Frame Difference', 800,600)
        cv2.resizeWindow('Security Camera Feed', 800,600)
      # uncomment to see the tresh and framedifference displays                  
        cv2.imshow("Thresh", thresh)
        cv2.imshow("Frame Difference", frameDiff)



        cv2.putText(frame, text, (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
        cv2.imshow("Security Camera Feed", frame)

        key = cv2.waitKey(3) & 0xFF
        if key == 27 or key == ord('q'):
            print("Bye")
            break

    camera.release()
cv2.destroyAllWindows()

此图显示了第一帧仍然影响帧差异结果,这会强制盒子覆盖没有运动的区域。

Result showing the frame difference and video display

这一个示出了忽略运动的情况,错误地检测到不再存在的运动(与视频的第二帧和第一帧的帧差异)。当我允许多次跟踪时,它会跟踪两者,这仍然是错误的,因为它检测到空白区域。

enter image description here

有没有人知道代码错误或缺乏的地方?我一直在努力,但无法让它正常工作。

提前谢谢!!

1 个答案:

答案 0 :(得分:1)

为了包含运动检测,我在 NPM Registry 和 docker hub 上创建了通用组件 这会检测客户端网络摄像头(React app)上的运动,并在基于开放 CV 的 Python 中使用服务器 所以客户端只捕获网络摄像头图像,服务器使用 OPENCV 分析这些图像以确定是否有运动 客户端可以指定服务器每次有动作时调用的回调函数 服务器只是一个 docker 镜像,您可以将其拉取和运行并将其 URL 指定给客户端

NPM 注册表(客户端)

注册链接:

https://www.npmjs.com/settings/kunalpimparkhede/packages

命令

npm install motion-detector-client

Docker 镜像(服务器)

链接

https://hub.docker.com/r/kunalpimparkhede/motiondetectorwebcam

命令

docker pull kunalpimparkhede/motiondetectorwebcam

您只需要编写以下代码即可进行运动检测

用法:

import MotionDetectingClient from './MotionDetectingClient';

<MotionDetectingClient server="http://0.0.0.0:8080" callback={handleMovement}/>

function handleMovement(pixels) 
{
console.log("Movement By Pixel="+pixels)
}

在服务器端:只需在端口 8080 上启动 docker 服务器:

docker run --name motion-detector-server-app -P 8080:5000 motion-detector-server-app
相关问题