opencv-python 错位图片拼接

问题描述

我是 opencv 和 python 的新手。我尝试使用 opencv 拼接多个图像。但在某一时刻,缝合错位了。假设我有 97 张图像,拼接代码适用于 1-24 张图像,但是当需要 25 张图像拼接时,就会出现问题。如果我对 23-97 个图像中的图像执行相同的代码,拼接不会错位。我无法理解从第 1 个图像开始拼接第 25 个图像时哪些细节出错,以及为什么它适用于 23-97 个图像。

代码如下:

# find the keypoints and descriptors with SIFT
    gray1 = cv2.cvtColor(image1,cv2.COLOR_BGR2GRAY)
    ret1,mask1 = cv2.threshold(gray1,1,255,cv2.THRESH_BINARY)
    kp1,descriptors1 = detector.detectAndCompute(gray1,mask1)

    gray2 = cv2.cvtColor(image2,cv2.COLOR_BGR2GRAY)
    ret2,mask2 = cv2.threshold(gray2,cv2.THRESH_BINARY)
    kp2,descriptors2 = detector.detectAndCompute(gray2,mask2)

    keypoints1Im = cv2.drawKeypoints(image1,kp1,outimage = cv2.DRAW_MATCHES_FLAGS_DEFAULT,color=(0,255))
    keypoints2Im = cv2.drawKeypoints(image2,kp2,255))

    matcher = cv2.BFMatcher()
    matches = matcher.knnMatch(descriptors2,descriptors1,k=2)

    good = []
    for m,n in matches:
        if m.distance < 0.75 * n.distance:
            good.append(m)

    print (str(len(good)) + " Matches were Found")

    if len(good) <= 10:
        return image1

    matches = copy.copy(good)

    matchDrawing = util.drawMatches(gray2,gray1,matches)
    
    src_pts = np.float32([ kp2[m.queryIdx].pt for m in matches ]).reshape(-1,2)
    dst_pts = np.float32([ kp1[m.trainIdx].pt for m in matches ]).reshape(-1,2)

    H = cv2.findHomography(src_pts,dst_pts,cv2.RANSAC,5.0)[0]

    h1,w1 = image1.shape[:2]
    h2,w2 = image2.shape[:2]
    pts1 = np.float32([[0,0],[0,h1],[w1,0]]).reshape(-1,2)
    pts2 = np.float32([[0,h2],[w2,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,t[0]],t[1]],1]]) # translate

    result = cv2.warpPerspective(image2,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]] = image1
    # Now create a mask of logo and create its inverse mask also
    img2gray = cv2.cvtColor(result,cv2.COLOR_BGR2GRAY)
    ret,mask = cv2.threshold(img2gray,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)

    return result

拼接24张图片时的特征匹配图片如下: Feature matching on 24 image

拼接25张图片时的特征匹配图片如下: Feature matching on 25 image

第 25 张图像后的图像拼接图像如下所示: 25 image stitching

拼接图像是什么意思/拼接25张图像后显示的,叫什么?哪里出了问题,特征匹配/单应矩阵/包装图像/图像透视/结果图像大小?

需要进行哪些更改才能使其正常工作?如果有人研究过 opencv-python 并且知道这种拼接逻辑,请指导并帮助我。我正在努力使这项工作发挥作用,但无法做到这一点。

谢谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)