Python计算机视觉 BoF(Bag of features)图像检索

BoW模型最早应用于文本处理领域,用来对文档进行分类和识别。BoW模型因为其简单有效的有点得到广泛的应用,并在计算机视觉领域应用,进行图像处理和识别。

为了表示一幅图像,我们可以将图像看作文档,即若干个“视觉词汇”的集合,同样的,视觉词汇相互之间没有顺序。我们可以把这些不同实例之间共同的部位提取出来,作为识别这一类目标的视觉词汇。而SIFT算法是提取图像中局部不变特征的应用最广泛的算法,因此我们可以用SIFT算法从图像中提取不变特征点,作为视觉词汇,并构造单词表,用单词表中的单词表示一幅图像。

一、基础流程

1.特征提取
特征提取和描述的主要任务是从图像中抽取具有代表性的局部特征。要求这些特征具有较强的可区分性,能最大限度地与其他物体进行区分。此外,还要求被提取的特征具有较好的稳定性,此类特征经常存在于图像的高对比度区域,例如物体边缘与角点。在这里插入图片描述
2.学习 “视觉词典”
利用聚类算法(如:K-Means算法)对步骤1提取的特征描述子构造单词表(词典),特征描述子分为K个簇,以使簇内具有较高的相似度,而簇间相似度较低,将词义相近的词汇合并,作为单词表中的基础词汇,聚类类别的数量K即为整个视觉词典的大小基础词汇的个数。
在这里插入图片描述
K-means 聚类算法
算法流程:
• 随机初始化 K 个聚类中心
• 重复下述步骤直至算法收敛:
• 对应每个特征,根据距离关系赋值给某个中心/类别
• 对每个类别,根据其对应的特征集重新计算聚类中心

3. 针对输入特征集,根据视觉词典进行量化
应选择合适的视觉词典/码本的规模,因为:
•太少:视觉单词无法覆盖所有可能出现的情况
•太多: 计算量大,容易过拟合

4. 把输入图像,根据TF-IDF转化成视觉单词的频率直方图
在这里插入图片描述
5. 构造特征到图像的倒排表,通过倒排表快速索引相关图像
利用倒排表进行计算新图像与数据库中所有图像之间的相似性。

6. 根据索引结果进行直方图匹配在这里插入图片描述

二、算法实现

1.生成代码所需要的文件模型

# -*- coding: utf-8 -*-
import pickle
from PCV.imagesearch import vocabulary
from PCV.tools.imtools import get_imlist
from PCV.localdescriptors import sift
##要记得将PCV放置在对应的路径下
#获取图像列表
imlist = get_imlist('D:/Visual_Studio_Code/data/first1000/') ###要记得改成自己的路径
nbr_images = len(imlist)
#获取特征列表
featlist = [imlist[i][:-3]+'sift' for i in range(nbr_images)]
#提取文件夹下图像的sift特征
for i in range(nbr_images):
    sift.process_image(imlist[i], featlist[i])
#生成词汇
voc = vocabulary.Vocabulary('ukbenchtest')
voc.train(featlist, 1000, 10)
#保存词汇
# saving vocabulary
with open(r'D:\Visual_Studio_Code\data\first1000\vocabulary.pkl', 'wb') as f:
    pickle.dump(voc, f)
print ('vocabulary is:', voc.name, voc.nbr_words)

生成视觉词典
在这里插入图片描述
2.将模型数据导入数据库

# -*- coding: utf-8 -*-
import pickle
from PCV.imagesearch import imagesearch
from PCV.localdescriptors import sift
from sqlite3 import dbapi2 as sqlite
from PCV.tools.imtools import get_imlist
##要记得将PCV放置在对应的路径下
#获取图像列表
imlist = get_imlist('D:/Visual_Studio_Code/data/first1000/')##记得改成自己的路径
nbr_images = len(imlist)
#获取特征列表
featlist = [imlist[i][:-3]+'sift' for i in range(nbr_images)]
# load vocabulary
#载入词汇
with open(r'D:\Visual_Studio_Code\data\first1000\vocabulary.pkl', 'rb') as f:
    voc = pickle.load(f)
#创建索引
indx = imagesearch.Indexer('testImaAdd.db',voc)
indx.create_tables()
# go through all images, project features on vocabulary and insert
#遍历所有的图像,并将它们的特征投影到词汇上
for i in range(nbr_images)[:1000]:
    locs,descr = sift.read_features_from_file(featlist[i])
    indx.add_to_index(imlist[i],descr)
# commit to database
#提交到数据库
indx.db_commit()
con = sqlite.connect('testImaAdd.db')
print (con.execute('select count (filename) from imlist').fetchone())
print (con.execute('select * from imlist').fetchone())

生成一个数据库文件
在这里插入图片描述
3.测试

# -*- coding: utf-8 -*-
import pickle
from PCV.localdescriptors import sift
from PCV.imagesearch import imagesearch
from PCV.geometry import homography
from PCV.tools.imtools import get_imlist

# load image list and vocabulary
#载入图像列表
imlist = get_imlist('first1000/')
nbr_images = len(imlist)
#载入特征列表
featlist = [imlist[i][:-3]+'sift' for i in range(nbr_images)]

#载入词汇
with open('first1000/vocabulary.pkl', 'rb') as f:
    voc = pickle.load(f)

src = imagesearch.Searcher('testImaAdd.db',voc)

# index of query image and number of results to return
#查询图像索引和查询返回的图像数
q_ind = 0
nbr_results = 20

# regular query
# 常规查询(按欧式距离对结果排序)
res_reg = [w[1] for w in src.query(imlist[q_ind])[:nbr_results]]
print ('top matches (regular):', res_reg)

# load image features for query image
#载入查询图像特征
q_locs,q_descr = sift.read_features_from_file(featlist[q_ind])
fp = homography.make_homog(q_locs[:,:2].T)

# RANSAC model for homography fitting
#用单应性进行拟合建立RANSAC模型
model = homography.RansacModel()
rank = {}

# load image features for result
#载入候选图像的特征
for ndx in res_reg[1:]:
    locs,descr = sift.read_features_from_file(featlist[ndx])  # because 'ndx' is a rowid of the DB that starts at 1
    # get matches
    matches = sift.match(q_descr,descr)
    ind = matches.nonzero()[0]
    ind2 = matches[ind]
    tp = homography.make_homog(locs[:,:2].T)
    # compute homography, count inliers. if not enough matches return empty list
    try:
        H,inliers = homography.H_from_ransac(fp[:,ind],tp[:,ind2],model,match_theshold=4)
    except:
        inliers = []
    # store inlier count
    rank[ndx] = len(inliers)

# sort dictionary to get the most inliers first
sorted_rank = sorted(rank.items(), key=lambda t: t[1], reverse=True)
res_geom = [res_reg[0]]+[s[0] for s in sorted_rank]
print ('top matches (homography):', res_geom)

# 显示查询结果
imagesearch.plot_results(src,res_reg[:8]) #常规查询
imagesearch.plot_results(src,res_geom[:8]) #重排后的结果

运行结果:
在这里插入图片描述
在这里插入图片描述

三、小结

由于自己收集的数据实验结果较不理想,个人推测是因为收集的数据太少,不能有效搜索,若增加图库中的照片会使视觉字典更加丰富,让图像检索效果更加理想。有待调试,会尽快更新。

猜你喜欢

转载自blog.csdn.net/weixin_43848422/article/details/90147395