Leichti
Leichti

Reputation: 93

Image Stitching opencv

I'm trying to stitch two images together using OpenCV's Stitcher class, but despite getting good matches between the two images, the stitching process fails. I've checked my code and the matches seem to be correct, but the Stitcher returns an error.

Here's my code:

import cv2

img1 = cv2.imread('eleImages/2.jpeg')
img2 = cv2.imread('eleImages/1.jpeg')

gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)

sift = cv2.SIFT_create(nfeatures=35000)
kp1, des1 = sift.detectAndCompute(gray1, None)
kp2, des2 = sift.detectAndCompute(gray2, None)

if des1 is not None and des2 is not None and len(des1) > 0 and len(des2) > 0:
    bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=False)
    matches = bf.knnMatch(des1, des2, k=2)

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

    good_matches = sorted(good_matches, key=lambda x: x.distance)[:200]

    matches_Image = cv2.drawMatches(img1, kp1, img2, kp2, good_matches, None, flags=cv2.DrawMatchesFlags_DEFAULT)
    cv2.imwrite('PanoramasAndMatches/Matches.jpeg', matches_Image)
    imgs = [img1, img2]

    stitcher = cv2.Stitcher_create(mode=cv2.Stitcher_SCANS)
    stitcher.setPanoConfidenceThresh(0.2)

    status, stitched_img = stitcher.stitch(imgs)

    if status != cv2.Stitcher_OK:
        print(f"Stitching failed with status {status}.")
        if status == 1:
            print("Homography estimation failed.")
        elif status == 2:
            print("Camera parameters adjustment failed.")
        else:
            print("Unknown stitching error.")
    else:
        cv2.imwrite('PanoramasAndMatches/Stitched_Image.jpeg', stitched_img)
        print("Stitching successful")

The matches image looks good, with many correct matches between the two images. However, when I try to stitch the images together using the Stitcher class, it fails with a status code of 1 (Homography estimation failed) and sometimes with a status code of 3.

I've checked the documentation and examples, but I can't seem to find what's going wrong. Has anyone else encountered this issue? Any help would be greatly appreciated!

Images are uploaded here: https://imgur.com/a/R5lV32C

Edit:

I've been trying to troubleshoot the issue with the Stitcher class, but I'm still stuck. Is there a way that I can use the matched lines to "hint" to the Stitcher class how to align the images, rather than relying solely on its internal homography estimation algorithm? Any suggestions or guidance would be greatly appreciated!

Upvotes: 2

Views: 192

Answers (0)

Related Questions