教学文库网 - 权威文档分享云平台
您的当前位置:首页 > 精品文档 > 学前教育 >

OpenCV特征提取与图像检索实现(附代码)(2)

来源:网络收集 时间:2026-07-12
导读: with open(pickled_db_path) as fp: self.data = pickle.load(fp) self.names = [] self.matrix = [] for k, v in self.data.iteritems(): self.names.append(k) self.matrix.append(v) self.matrix = np.array(sel

with open(pickled_db_path) as fp: self.data = pickle.load(fp) self.names = [] self.matrix = []

for k, v in self.data.iteritems(): self.names.append(k) self.matrix.append(v) self.matrix = np.array(self.matrix) self.names = np.array(self.names)

def cos_cdist(self, vector):

# getting cosine distance between search image and images database

#计算待搜索图像与数据库图像的余弦距离

v = vector.reshape(1, -1)

return scipy.spatial.distance.cdist(self.matrix, v, 'cosine').reshape(-1)

def match(self, image_path, topn=5): features = extract_features(image_path) img_distances = self.cos_cdist(features) # getting top 5 records

# 获得前5个记录 nearest_ids =

np.argsort(img_distances)[:topn].tolist()

nearest_img_paths = self.names[nearest_ids].tolist()

return nearest_img_paths,

img_distances[nearest_ids].tolist()这里要加载前一步得到的特征向量,并从它们中创建一个大矩阵,然后计算待搜索图像的特征向量和特征向量数据库之间的余弦距离,然后输出最近的前N个结果。当然,这仅仅是一个demo,在实际计算中,还可以用一些算法来快速计算数百万图像间的余弦距离。你可以使用简单且运行速度相当快的Annoy Index(在1M图像中搜索约需2ms)。 现在把它们放在一起运行一下: def show_img(path):

img = imread(path, mode='RGB') plt.imshow(img) plt.show() def run():

images_path = 'resources/images/'

files = [os.path.join(images_path, p) for p in sorted(os.listdir(images_path))] # getting 3 random images

# 随机获取3张图 sample = random.sample(files, 3)

batch_extractor(images_path)

ma = Matcher('features.pck')

for s in sample: print 'Query image

==========================================' show_img(s)

names, match = ma.match(s, topn=3) print 'Result images

========================================' for i in range(3):

# we got cosine distance, less cosine distance between vectors

# more they similar, thus we subtruct it from 1 to get match value#我们得到了余弦距离,向量之间

的余弦距离越小表示它们越相似,因此我们从1中减去它以得到匹配值

print 'Match %s' % (1-match[i]) show_img(os.path.join(images_path, names[i]))

run()大家可以在我的 github上下载源码,或者在Google Colab上运行(Google Colab是一种提供GPU在线计算的免费服务):

https://colab.research.google.com/drive/1BwdSConGugBlGzPLLkXHTz2ahkdzEhQ9 ▌总结

在运行上述代码的过程中,你可能会发现搜索到的相似图像并不总能达到我们想象中的那种相似程度。这是因为我们所用的这种算法是上下文无关(context-unaware)的,所以该算法在寻找相同(即使是被修改过的)图像方面表现更好,而不是在相似图像方面。如果是要寻找上下文相关的相似图像,那就要使用卷积神经网络了,我的下一篇文章会对这方面的知识进行详细介绍。 作者:Andrey Nikishaev

…… 此处隐藏:259字,全部文档内容请下载后查看。喜欢就下载吧 ……
OpenCV特征提取与图像检索实现(附代码)(2).doc 将本文的Word文档下载到电脑,方便复制、编辑、收藏和打印
本文链接:https://www.jiaowen.net/wendang/598279.html(转载请注明文章来源)
Copyright © 2020-2025 教文网 版权所有
声明 :本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载的作品侵犯了您的权利,请在一个月内通知我们,我们会及时删除。
客服QQ:78024566 邮箱:78024566@qq.com
苏ICP备19068818号-2
Top
× 游客快捷下载通道(下载后可以自由复制和排版)
VIP包月下载
特价:29 元/月 原价:99元
低至 0.3 元/份 每月下载150
全站内容免费自由复制
VIP包月下载
特价:29 元/月 原价:99元
低至 0.3 元/份 每月下载150
全站内容免费自由复制
注:下载文档有可能出现无法下载或内容有问题,请联系客服协助您处理。
× 常见问题(客服时间:周一到周五 9:30-18:00)