如何加速这个opencv python代码?

时间:2016-04-13 17:37:31

标签: python-2.7 opencv

`import cv2
import numpy as np

cap = cv2.VideoCapture(0)
_, back = cap.read()
back=cv2.cvtColor(back,cv2.COLOR_BGR2GRAY)
back = cv2.GaussianBlur(back,(5,5),0)
ret,back = cv2.threshold(back,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
kernel = np.ones((5,5),np.uint8)
#back = cv2.erode(th2,kernel,iterations = 3)
while(1):

    # Take each frame
    _, video = cap.read()

    img=cv2.cvtColor(video,cv2.COLOR_BGR2GRAY)
    img = cv2.GaussianBlur(img,(5,5),0)
    ret,mask1 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    #kernel = np.ones((5,5),np.uint8)
    #mask1 = cv2.erode(th3,kernel,iterations = 3)
    mask=mask1
    #img2=cv2.bitwise_and(mask1,back,mask = mask)
    #mask=mask-img2
    final=np.zeros((480,640,1), np.uint8)
    m=0
    n=0

    for i in range (477):
        c=0
        for j in range(637):
            if abs(back[i,j]-mask[i,j])<5:
                mask.itemset(i,j,0)
                if mask.item(i,j)==mask.item(i,j+1):
                    continue
                if c==0:
                    m=j
                    c=c+1
                    continue

                if c==1:
                    n=j+1
                    #print i,(m+n)//2
                    final.itemset(i,(m+n)//2,0,255)

    '''cv2.namedWindow('subtracted',cv2.WINDOW_NORMAL)
    cv2.imshow('subtracted', mask1)
    '''
    cv2.namedWindow('actual',cv2.WINDOW_NORMAL)
    cv2.imshow('actual', mask)
    '''cv2.namedWindow('initial',cv2.WINDOW_NORMAL)
    cv2.imshow('initial', back)
    '''
    cv2.namedWindow('final',cv2.WINDOW_NORMAL)
    cv2.imshow('final', final)

    k = cv2.waitKey(1) & 0xFF
    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()`

我写这个用于3d扫描。它必须减去背景并给出一条薄的激光线。 它花费了大量时间并且给出了运行时错误(ubytes标量中遇到溢出)。我们可以优化它吗?

0 个答案:

没有答案