ORB 算法实现图像匹配 - 识别图片并绘制边框

本篇文章使用 ORB 算法实现图像匹配功能,并使用 Python 的 OpenCV 库绘制识别图片的边框。

代码示例

import cv2
import numpy as np

# 读取大图和小图
large_image = cv2.imread('IMG/phone4.png')  # 图形都是24位
small_image = cv2.imread('IMG/click/X1.png')  # 图形都是24位

# 调整小图尺寸与大图一致
small_image = cv2.resize(small_image, (large_image.shape[1], large_image.shape[0]))

orb = cv2.ORB_create()

# 在大图中检测特征点和描述符
kp1, des1 = orb.detectAndCompute(large_image, None)

# 在小图中检测特征点和描述符
kp2, des2 = orb.detectAndCompute(small_image, None)

bF = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

# 特征匹配
matches = bF.match(des1, des2)

# 根据距离进行排序
matches = sorted(matches, key=lambda x: x.distance)

# 选择前 n 个最佳匹配
n = 10
best_matches = matches[:n]

# 获取最佳匹配的特征点坐标
src_pts = np.float32([kp1[m.queryIdx].pt for m in best_matches]).reshape(-1, 1, 2)
dst_pts = np.float32([kp2[m.trainIdx].pt for m in best_matches]).reshape(-1, 1, 2)

# 使用cv2.findHomography函数计算透视变换矩阵
# 计算透视变换矩阵
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)

# 获取小图的宽度和高度
h, w = small_image.shape[:2]

# 定义小图的四个角点坐标
pts = np.float32([[0, 0], [0, h], [w, h], [w, 0]]).reshape(-1, 1, 2)

# 通过透视变换将小图的四个角点映射到大图中
dst = cv2.perspectiveTransform(pts, M)

# 在大图中绘制匹配的边框
cv2.polylines(large_image, [np.int32(dst)], True, (0, 255, 0), 2, cv2.LINE_AA)

# 显示结果
cv2.imshow('Result', large_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

错误排查

  • 类型不匹配或尺寸不一致: 确保 large_imagesmall_image 的类型相同,且尺寸一致。可以使用 cv2.resize 函数调整小图像的尺寸。

  • 路径错误: 检查 large_imagesmall_image 的路径是否正确,并确保两个图像都能够成功加载。

总结

本文介绍了使用 ORB 算法实现图像匹配功能的具体步骤,并提供了相应的代码示例和错误排查方法。通过学习本文,您可以快速上手使用 ORB 算法进行图像匹配操作。

ORB 算法实现图像匹配 - 识别图片并绘制边框

原文地址: https://www.cveoy.top/t/topic/lTPc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录