2017-04-18 152 views
-1

我在谷歌阅读OpenCV中,发现下面的示例代码在网上玩:opencv的蟒蛇背景减法和运动跟踪

import cv2 

def diffImg(t0, t1, t2): 
    d1 = cv2.absdiff(t2, t1) 
    d2 = cv2.absdiff(t1, t0) 
    return cv2.bitwise_and(d1, d2) 

cam = cv2.VideoCapture('vid1.mp4') 

winName = "Movement Indicator" 
cv2.namedWindow(winName, cv2.CV_WINDOW_AUTOSIZE) 

# Read three images first: 
t_minus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY) 
t = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY) 
t_plus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY) 

while True: 
    cv2.imshow(winName, diffImg(t_minus, t, t_plus)) 

    # Read next image 
    t_minus = t 
    t = t_plus 
    t_plus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY) 

    key = cv2.waitKey(10) 
    if key == 27: 
    cv2.destroyWindow(winName) 
    break 

print "Goodbye" 

它产生以下种类的样品视频输出的,我给它:opencv image difference frame output

所以我用这个脚本得到这样的结果。现在我试图弄清楚的是 - 1)获取视频文件中移动对象的边界矩形 2)将该边界矩形的内容从原始视频帧复制到另一个视频帧并将完成的视频写入文件

此外,在试图Kanishak Katahra的解决方案下面,我在下面的截图让在结果窗口中下面的输出在右侧的截图 -

+0

请问您可以减少您的问题到最小的可能主题吗?你问如何使用OpenCV写入电影文件?你在问如何使用OpenCV写入新窗口?你问如何将'diffImg'保存到一个变量来完成这些事情?最后,您能否编辑您的问题以包含指向您用于编写此脚本的资源的链接? – Seanny123

+0

我想从diffimg中剪切突出显示的部分,并仅将diffimg中突出显示的部分从原始帧复制到视频文件中 – DeadMan

+0

那么,您尝试完成此操作的是什么?当你看看diffImg的结果时,你能看到它可能被输入到视频文件中吗? – Seanny123

回答

0

制作的兴趣点在输出你获得1秒。使其余为0. 将其转换为与原始图像大小相同的3D数组。 将原始图像与您获得的输出相乘。

import cv2 
import numpy as np 
from numpy import newaxis 
import time 

def diffimg (a,b,c): 
    t0 = cv2.absdiff(a,b) 
    t1 = cv2.absdiff(b,c) 
    t3 = cv2.bitwise_and(t0,t1) 
    return t3 

cap = cv2.VideoCapture(0) 
t = cap.read() [1] 
tp = cap.read() [1] 
tpp = cap.read() [1] 

t = cv2.cvtColor(t,cv2.COLOR_BGR2GRAY) 
tp = cv2.cvtColor(tp,cv2.COLOR_BGR2GRAY) 
tpp = cv2.cvtColor(tpp,cv2.COLOR_BGR2GRAY) 


while True: 

    img = diffimg(t,tp,tpp) 
    cv2.imshow("motion detct",img) 

    key = cv2.waitKey(10) 


    res,img2 = cap.read() 
    #print img2.shape 

    t = tp 
    tp = tpp 
    tpp = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY) 

    cv2.imshow('image',img) 
    print img 
    img[img <= 10] = 0 #Try adjusting this value for better results. 
    img[img != 0] = 1 
    img = np.repeat(img[:, :, np.newaxis], 3, axis=2) 
    img3 = np.multiply(img,img2) 
    cv2.imshow('result',img3) 



    if key == 27: 
     cv2.destroyAllWindows() 
     break; 



print "Goodbye User" 
+0

嗨,用你的代码更新结果截图的问题。我想要做的是抓住结果窗口中的图像窗口中可见的区域,以便它现在在结果窗口中显示所有颜色和内部细节,它仅显示像素化的边界我认为移动的对象 – DeadMan

+0

它为您提供已更改的像素。当您将一个单色物体移动一小段距离时,没有多少像素会发生变化。这就是你得到这种产出的原因。尝试使用较小且丰富多彩的对象的相同代码以获得更好的结果。 –

+0

为了更清楚地理解,在res之前包含一个0.5秒的延迟,img2 = cap.read()。 –