import cv2 import numpy as np import time import os def sift_feature_extraction(image_path): # 读取图像 img = cv2.imread(image_path) if img is None: print("无法加载图像,请检查路径") return # 转换为灰度图 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 创建SIFT对象 sift = cv2.SIFT_create() # 记录开始时间 start_time = time.time() # 检测关键点和描述符 keypoints, descriptors = sift.detectAndCompute(gray, None) # 计算耗时 end_time = time.time() processing_time = end_time - start_time # 绘制关键点 img_with_keypoints = cv2.drawKeypoints( gray, keypoints, img, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ) # 创建输出目录 output_dir = "output/sift_results" os.makedirs(output_dir, exist_ok=True) # 保存结果 output_path = os.path.join(output_dir, "sift_result.jpg") cv2.imwrite(output_path, img_with_keypoints) # 输出结果信息 print(f"检测到 {len(keypoints)} 个关键点") print(f"描述符形状: {descriptors.shape if descriptors is not None else 'None'}") print(f"特征提取耗时: {processing_time:.4f} 秒") print(f"结果已保存至: {output_path}") # 显示结果(可选) cv2.imshow('SIFT Features', img_with_keypoints) cv2.waitKey(0) cv2.destroyAllWindows() if __name__ == "__main__": # 示例用法 image_path = "../data/image.jpg" # 需要替换为实际图像路径 print("开始SIFT特征提取...") sift_feature_extraction(image_path)