python - OpenCV、ORB 检测:与多个图像相比,如何返回最佳匹配?
问题描述
在将此图像与数组中的多个图像进行比较时,我试图从输入图像中获得最佳匹配,更具体地说 - 尝试分析书籍封面并将其与数组中的书籍封面进行比较 - 返回正确的图像。我想到了两种方法,但我不完全确定如何。
import cv2
import numpy as np
import matplotlib.pyplot as plt
import time
class imageCapture(object):
def __init__(self):
self.image = None
self.storedImages = [r'C:\pythonImg\image1.jpg']
def captureImage(self):
time.sleep(2)
cap = cv2.VideoCapture(0)
if cap.isOpened():
ret, frame = cap.read()
print("The image has been captured: " + str(ret))
else:
ret = False
img1 = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) #this converts the colours to RGB from BGR
self.image = img1
def get_Matches_Orb(self): #at this point in time we are comparing it to a saved path image - eventually save the vectors
#trainImg = cv2.imread(self.image,0)
for image in self.storedImages:
storedImg = cv2.imread(image,0)
orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(self.image,None) #this finds keypoints and descriptors with SIFT
kp2, des2 = orb.detectAndCompute(storedImg,None)
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) #create a bfMatcher object
matches = bf.match(des1,des2) #Match descriptors
matches = sorted(matches, key = lambda x:x.distance) #sorts them in order of their distance - lowest distance first.
sum = 0
for i in matches:
sum = sum + i.distance
avg = sum / len(matches)
print(avg)
#print(avg.distance)
img3 = cv2.drawMatches(self.image,kp1,storedImg,kp2,matches[:10],None, flags=2) #helps us to draw the matches.
plt.imshow(img3)
plt.show()
testobj = imageCapture()
testobj.captureImage()
testobj.get_Matches_Orb()
我的一个想法是获取 DMatch 返回的平均距离,DMatch.distance
并返回平均距离最低的图像——到目前为止,我只生成了平均值并使用不同的书籍封面对其进行了测试。将其与正确的书籍封面进行比较时,平均距离实际上确实显得更低,但我想知道这是否准确。这让我想到了一个问题:有没有办法使用存储在 kp1 和 kp2 中的关键点来更准确地比较图像?
解决方案
比较所有匹配距离是一个坏主意,因为这种方法有很多异常值。
你需要做的是使用 findHomography。这将为您提供当前图像和字典图像之间的转换。
然后你必须选择一些参数来验证或拒绝这个单应性。
最简单的方法(对我而言)是将字典中的一个框投影到您当前的图像中,并尝试查看框的形状是否足够好(或不够好)(区域是否在良好的范围内?,允许角度的角落? ETC..)。或者您可以设置内部数量的阈值,它们的重新分区等......
为了使某些东西变得健壮,您可能会使用几个标准
看看这个教程。他们使用了 surf 关键点,但您可以使用 orb 代替。https://docs.opencv.org/2.4/doc/tutorials/features2d/feature_homography/feature_homography.html
推荐阅读
- python-3.x - 当我尝试在虚拟环境中通过“pip3 install translate”安装包(翻译)时出现错误
- php - Eloquent API 资源 - 将资产链接添加到嵌套值
- javascript - Mongoose 找不到所需的输出
- python - (已解决)Tensorflow 联合 | tff.learning.from_keras_model() 具有具有 DenseFeature 层和多个输入的模型
- cassandra - Apache Cassandra 3.11.4 是否支持每个节点超过 1TB 的存储?
- java - 在flyway java迁移中检索属性
- javascript - 使用不同的变量调用相同的函数 - 简化代码
- python - MATLAB和python中BCH代码的区别
- c# - 在 ListView Winform 中显示数据库中的多个列
- php - 如何将 SQS 延迟时间增加到 900 秒以上