gpt4 book ai didi

python - AttributeError: 'tuple' 对象没有属性 'sort'

转载 作者:行者123 更新时间:2023-12-05 03:20:31 26 4
gpt4 key购买 nike

这是我的代码,我收到一个 AttributeError: 'tuple' object has no attribute 'sort.我正在尝试进行图像对齐,并在一篇文章中找到了这个标准图像对齐代码。我正在学习 openCV 和 python,我也是新手,我现在可以用 openCV 做一些基本的事情,我正在尝试学习图像对齐,但我被困在了这部分。

Traceback (most recent call last):
File "test9.py", line 31, in <module>
matches.sort(key = lambda x: x.distance)
AttributeError: 'tuple' object has no attribute 'sort'


------------------
(program exited with code: 1)
Press return to continue


import cv2
import numpy as np

# Open the image files.
img1_color = cv2.imread("/home/pi/Desktop/Project AOI/testboard1/image_2.jpg") # Image to be aligned.
img2_color = cv2.imread("/home/pi/Desktop/Project AOI/testboard1/image_0.jpg") # Reference image.

# Convert to grayscale.
img1 = cv2.cvtColor(img1_color, cv2.COLOR_BGR2GRAY)
img2 = cv2.cvtColor(img2_color, cv2.COLOR_BGR2GRAY)
height, width = img2.shape

# Create ORB detector with 5000 features.
orb_detector = cv2.ORB_create(5000)

# Find keypoints and descriptors.
# The first arg is the image, second arg is the mask
# (which is not required in this case).
kp1, d1 = orb_detector.detectAndCompute(img1, None)
kp2, d2 = orb_detector.detectAndCompute(img2, None)

# Match features between the two images.
# We create a Brute Force matcher with
# Hamming distance as measurement mode.
matcher = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck = True)

# Match the two sets of descriptors.
matches = matcher.match(d1, d2)

# Sort matches on the basis of their Hamming distance.
matches.sort(key = lambda x: x.distance)

# Take the top 90 % matches forward.
matches = matches[:int(len(matches)*0.9)]
no_of_matches = len(matches)

# Define empty matrices of shape no_of_matches * 2.
p1 = np.zeros((no_of_matches, 2))
p2 = np.zeros((no_of_matches, 2))

for i in range(len(matches)):
p1[i, :] = kp1[matches[i].queryIdx].pt
p2[i, :] = kp2[matches[i].trainIdx].pt

# Find the homography matrix.
homography, mask = cv2.findHomography(p1, p2, cv2.RANSAC)

# Use this matrix to transform the
# colored image wrt the reference image.
transformed_img = cv2.warpPerspective(img1_color,
homography, (width, height))

# Save the output.
cv2.imwrite('output.jpg', transformed_img)

最佳答案

您将返回一个元组,而不是一个列表。你不能只是 matches.sort(...) 那个。

OpenCV,自 v4.5.4 以来,在其 Python 绑定(bind)生成中表现出这种行为。

你必须改用这个:

matches = sorted(matches, ...)

这将创建一个新列表,其中包含原始元组的已排序元素。

相关问题:

关于python - AttributeError: 'tuple' 对象没有属性 'sort',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73157702/

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