Сшивание изображений OpenCV не дает правильного вывода - PullRequest
0 голосов
/ 21 января 2020

Я работаю над созданием приложения для сшивания изображений, находя ключевые точки и сшивая два изображения, используя opencv в python. Я использую код, доступный онлайн, чтобы сначала практиковаться и понимать. Работает хорошо, пока не идентифицирует перекрывающуюся область между двумя изображениями. Но окончательно сшитое изображение не правильное. Я получаю только полное левое изображение. изображение четырех шагов Может кто-нибудь подсказать, в чем проблема

Код приведен ниже:

import cv2
import numpy as np

# Read, Resize images and convert to Gray Scale

img1 = cv2.imread('mickey_left.png')
img1_o = cv2.resize(img1, (0,0), fx=1, fy=1)
img1_g = cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)

img2 = cv2.imread('mickey_right.png')
img2_o = cv2.resize(img2, (0,0), fx=1, fy=1)
img2_g = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)


# find the key points and descriptors with KAZE for Image Left & Right
kaze = cv2.KAZE_create()
(kp1, desc1) = kaze.detectAndCompute(img1_g, None)
print("# kps: {}, descriptors: {}".format(len(kp1), desc1.shape))

(kp2, desc2) = kaze.detectAndCompute(img2_g, None)
print("# kps: {}, descriptors: {}".format(len(kp2), desc2.shape))

#show key points
cv2.imshow('org_image_left_keypoints',cv2.drawKeypoints(img1_o,kp1,None))

#we will find correspondences between the key points & descriptor of two images using BFMatcher method
#we set parameter k=2, to get two best matches
bf = cv2.BFMatcher()
matches = bf.knnMatch(desc1,desc2, k=2)

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

# To draw the lines on matching images..
 # draw matches in green color

draw_params = dict(matchColor = (0,255,0),
                   singlePointColor = None,
                   flags = 2)
img3 = cv2.drawMatches(img1_o,kp1,img2_o,kp2,good,None,**draw_params)
cv2.imshow("original_image_drawMatches.jpg", img3)

#align the images.. homography matrix requires at least 10 matches
#homography matrix will be used with best matching points, 
#to estimate a relative orientation transformation within the two images

MIN_MATCH_COUNT = 10
if len(good) > MIN_MATCH_COUNT:
    src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)  # Source taken as Left image
    dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)  # Destination taken as Right image 
    M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,5.0)
    h,w,_ = img1_o.shape
    pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2)
    dst = cv2.perspectiveTransform(pts,M)
    img4 = cv2.polylines(img2_o,[np.int32(dst)],True,255,3, cv2.LINE_AA)
    cv2.imshow("original_image_overlapping.jpg", img4)
else:
    print ("Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT))


# after establishing a homography we need to to warp perspective, 
# essentially change the Field of View, we apply following homography matrix to the image 
#the overlap region is given below, using warpPerspective

dst = cv2.warpPerspective(img2_o,M,(img1_o.shape[1] + img2_o.shape[1], img1_o.shape[0]))
dst[0:img1_o.shape[0], 0:img1_o.shape[1]] = img1_o

cv2.imshow("original_img2_stitched.jpg", dst)

    enter code here

#cv2.imshow('Right Image', img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
...