gpt4 book ai didi

python - OpenCV warpPerspective 不适用于单应性

转载 作者:太空宇宙 更新时间:2023-11-03 22:36:23 29 4
gpt4 key购买 nike

我正在尝试使用 OpenCV 3,特别是 SIFT 功能、findHomography 和 warpPerspective,以便在更大的 image2 中找到 image1,然后对 image2 进行透视变换,使其(几乎)等于 image1。

这是代码:

import numpy as np
import cv2
from matplotlib import pyplot as plt

MIN_MATCH_COUNT = 10

img1 = cv2.imread('box.png',0) # queryImage
img2 = cv2.imread('box_in_scene.png',0) # trainImage

# Initiate SIFT detector
detector = cv2.xfeatures2d.SIFT_create()

# find the keypoints and descriptors with SIFT
kp1, des1 = detector.detectAndCompute(img1, None)
print("Image 1: # kps: {}, descriptors: {}".format(len(kp1), des1.shape))
kp2, des2 = detector.detectAndCompute(img2, None)
print("Image 2: # kps: {}, descriptors: {}".format(len(kp2), des2.shape))

FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks = 50)

flann = cv2.FlannBasedMatcher(index_params, search_params)

matches = flann.knnMatch(des1, des2, k=2)

# store all the good matches as per Lowe's ratio test.
good = []
for m,n in matches:
if m.distance < 0.7 * n.distance:
good.append(m)

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 = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
else:
print("Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT))

im_out = cv2.warpPerspective(img2, M, (img1.shape[1] * 2, img1.shape[0] * 2))
plt.imshow(im_out)
#plt.imshow(img2)
plt.show()

生成的图像仅略微扭曲但不足以匹配 img1。

这是匹配结果和变形(?)结果。

Matching result

Warped (?) result

最佳答案

我解决了这个问题。我在错误的方向上做单应性。应该是:

    M, mask = cv2.findHomography(dst_pts, src_pts, cv2.RANSAC, 5.0)

代替:

    M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)

Right warped result

关于python - OpenCV warpPerspective 不适用于单应性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58097148/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com