2016-07-29 80 views
0

我正在使用OpenCV拼接多個圖像。它開始工作,但我遇到了一件事情。 cv2.warpPerspective圖像之後有一個「軟」邊框,這意味着計算的蒙版是一個像素太大。圖像拼接神器[OpenCV Python]

我的代碼:

# apply a perspective warp to stitch the images 
    # together 
    result = cv2.warpPerspective(imageA, H, 
     (imageA.shape[1] + imageB.shape[1], imageA.shape[0])) 

    # Now create a mask of logo and create its inverse mask also 
    img2gray = cv2.cvtColor(result,cv2.COLOR_BGR2GRAY) 
    ret, mask = cv2.threshold(img2gray, 0, 255, cv2.THRESH_BINARY) 
    mask_inv = cv2.bitwise_not(mask) 

    resizedB = np.zeros((result.shape[0],result.shape[1],3), np.uint8) 
    resizedB[0:imageB.shape[0], 0:imageB.shape[1]] = imageB 
    difference = cv2.bitwise_or(resizedB,result, mask=mask_inv) 

    result = cv2.add(result,difference) 
    cv2.imwrite('result .jpg', result) 

我不得不使用cv2.bitwise_or因爲使用cv2.add將兩個圖像使得它太亮,這使得在連接幾乎黑線。 你有什麼想法如何解決這個問題?也許有一種方法可以修改遮罩,使其縮小1個像素?

+0

你可以使用一個梯度面具在轉變,換句話說,既融合對接面 – Pedro

+0

有沒有辦法用顏色閾值來獲得梯度面具?我不認爲有。你知道任何其他方式來獲得這樣的面具使用給定的圖片嗎? – Ekci

+0

你可以計算距離圖像邊界的距離,類似於http://stackoverflow.com/questions/37911062/how-to-obtain-the-right-alpha-value-to-perfectly-blend-two-images/37918596# 37918596並將其用作混合蒙版 – Micka

回答

0

我終於通過使用少量邏輯操作的組合來解決這個問題。解決辦法是介紹如下:

h1,w1 = imageB.shape[:2] 
    h2,w2 = imageA.shape[:2] 
    pts1 = np.float32([[0,0],[0,h1],[w1,h1],[w1,0]]).reshape(-1,1,2) 
    pts2 = np.float32([[0,0],[0,h2],[w2,h2],[w2,0]]).reshape(-1,1,2) 
    pts2_ = cv2.perspectiveTransform(pts2, H) 
    pts = np.concatenate((pts1, pts2_), axis=0) 
    # print("pts:", pts) 
    [xmin, ymin] = np.int32(pts.min(axis=0).ravel() - 0.5) 
    [xmax, ymax] = np.int32(pts.max(axis=0).ravel() + 0.5) 
    t = [-xmin,-ymin] 
    Ht = np.array([[1,0,t[0]],[0,1,t[1]],[0,0,1]]) # translate 

    result = cv2.warpPerspective(imageA, Ht.dot(H), (xmax-xmin, ymax-ymin)) 

    resizedB = np.zeros((result.shape[0], result.shape[1], 3), np.uint8) 

    resizedB[t[1]:t[1]+h1,t[0]:w1+t[0]] = imageB 
    # Now create a mask of logo and create its inverse mask also 
    img2gray = cv2.cvtColor(result,cv2.COLOR_BGR2GRAY) 
    ret, mask = cv2.threshold(img2gray, 0, 255, cv2.THRESH_BINARY) 

    kernel = np.ones((5,5),np.uint8) 
    k1 = (kernel == 1).astype('uint8') 
    mask = cv2.erode(mask, k1, borderType=cv2.BORDER_CONSTANT) 

    mask_inv = cv2.bitwise_not(mask) 

    difference = cv2.bitwise_or(resizedB, resizedB, mask=mask_inv) 

    result2 = cv2.bitwise_and(result, result, mask=mask) 

    result = cv2.add(result2, difference)