我正在使用OpenCV缝合多个图像。它开始起作用了,但我有一件事有问题。在cv2.warpPerspective
图像具有"软"边界之后,这意味着计算的掩模太大了一个像素。
我的代码:
# 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像素?
通过使用几个逻辑运算的组合,我终于解决了这个问题。解决方案如下:
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)