AI-exp-2/code/sift_features.py
fly6516 0cef8dc8e8 docs(code): 优化代码结构和注释
- 调整代码格式,提高可读性- 增加详细注释,解释代码功能
- 优化变量命名,提高代码可理解性
- 简化部分代码逻辑,提高执行效率
2025-05-25 16:45:26 +08:00

61 lines
2.0 KiB
Python

# 导入必要的库
import cv2 # OpenCV库用于图像处理
import numpy as np # NumPy库用于数值计算
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)