srcImg = cv.copyMakeBorder(img1, top, bot, left, right, cv.BORDER_CONSTANT, value=(0, 0, 0)) testImg = cv.copyMakeBorder(img2, top, bot, left, right, cv.BORDER_CONSTANT, value=(0, 0, 0)) img1gray = cv.cvtColor(srcImg, cv.COLOR_BGR2GRAY) img2gray = cv.cvtColor(testImg, cv.COLOR_BGR2GRAY) sift = cv.xfeatures2d.SIFT_create() height = srcImg.shape[0] width = srcImg.shape[1] if len(good) > MIN_MATCH_COUNT: src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2) dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2) M, mask = cv.findHomography(src_pts, dst_pts, cv.RANSAC, 5.0) warpImg = cv.warpPerspective(testImg, M, (testImg.shape[1], testImg.shape[0]), flags=cv.WARP_INVERSE_MAP) # 查找左边界 left = next((col for col in range(width) if srcImg[:, col].any() and warpImg[:, col].any()), None) # 查找右边界 right = next((col for col in range(width-1, -1, -1) if srcImg[:, col].any() and warpImg[:, col].any()), None) res = np.zeros([height, width, 3], np.uint8) for row in range(0, height): for col in range(0, width): if not srcImg[row, col].any(): res[row, col] = warpImg[row, col] elif not warpImg[row, col].any(): res[row, col] = srcImg[row, col] else: srcImgLen = float(abs(col - left)) testImgLen = float(abs(col - right)) alpha = srcImgLen / (srcImgLen + testImgLen) res[row, col] = np.clip(srcImg[row, col] * (1-alpha) + warpImg[row, col] * alpha, 0, 255) 中 为什么要用边界扩展,有什么用吗? 为什么不用的话会报溢出错误
时间: 2023-06-17 19:05:21 浏览: 42
在图像拼接中,我们需要将两张图像进行对齐,然后进行拼接。但是两张图像的大小可能不同,因此需要进行边界扩展,使得图像大小相同,扩展后的边界可以填充为黑色(或其他颜色)。
在代码中,使用边界扩展后,我们可以将两张图像进行逐像素的混合,通过计算每个像素在两张图像中的权重,将其进行加权混合,从而得到最终的拼接结果。如果不进行边界扩展,则在进行像素混合时,可能会出现数组越界的问题,导致溢出错误。
因此,边界扩展可以确保图像大小一致,从而避免数组越界问题,并且可以保证图像拼接的质量。