2016-07-29 78 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)