Dạ em up lại code lên đây ạ.
import cv2
import os
import numpy as np
# Load the query image
query_image = cv2.imread("../Dataset/Cat_55.jpg", cv2.IMREAD_GRAYSCALE)
# 1. Load the database images
database_images = []
folder_path = "../Dataset/"
for filename in os.listdir(folder_path):
if filename.endswith(".jpg"):
img_path = os.path.join(folder_path, filename)
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
database_images.append(img)
# 2. Create a SIFT object
sift = cv2.xfeatures2d.SIFT_create()
# Compute the keypoints and descriptors for the query image
query_keypoints, query_descriptors = sift.detectAndCompute(query_image, None)
# Compute the keypoints and descriptors for the database images
database_keypoints = []
database_descriptors = []
for img in database_images:
keypoints, descriptors = sift.detectAndCompute(img, None)
if descriptors is not None:
database_keypoints.append(keypoints)
database_descriptors.append(descriptors)
# Compute the distances between the query image and the database images
distances = []
for descriptors in database_descriptors:
# Ensure that both arrays have the same number of descriptors
num_descriptors = min(query_descriptors.shape[0], descriptors.shape[0])
query_descriptors_subset = query_descriptors[:num_descriptors]
descriptors_subset = descriptors[:num_descriptors]
# Compute the distances
distance = np.linalg.norm(query_descriptors_subset - descriptors_subset, axis=1)
distances.append(distance)
# 3. Sort the distances and retrieve the top N similar images
N = 5 # retrieve top 5 similar images
indices = np.argsort(distances)[:N]
# 4. Display the top N similar images
for i in indices:
img = database_images[i]
cv2.imshow(f"Similar image {i}", cv2.resize(img, (500, 500)))
cv2.waitKey(0)
cv2.destroyAllWindows()
Em ngồi sửa nãy giờ thì giờ code lại đang lỗi ở chỗ này ạ:
# 3. Sort the distances and retrieve the top N similar images
N = 5 # retrieve top 5 similar images
indices = np.argsort(distances)[:N]
Lỗi: ValueError: operands could not be broadcast together with shapes (1130,) (7024,)