Python计算机视觉编程_05
图像检索与识别
-
前言
-
1.Bag-of-words模型
-
2.Bag of features原理: 图像特征词典
-
- 2.1.特征提取
- 2.2.K-means聚类算法
- 2.3.图像检索
-
3.代码实现
-
- 3.1训练视觉词典
- 3.2.构建索引
- 3.3.检索图片
- 3.4.测试结果
-
4.总结
前言
之前介绍了计算机视觉的基础内容,本篇正式介绍计算机视觉一个应用广泛的内容,图像的检索与识别,这里我们使用的方法是由自然语言处理领域的Bag-of-words 模型改进而来的Bag of features。
1.Bag-of-words模型
在介绍Bag of features模型前,我们先介绍其原型Bag-of-words 模型。
Bagofwords模型,也叫做“词袋”,在信息检索中,Bag of words model假定对于一个文本,忽略其词序和语法、句法,将其仅仅看做是一个词集合,或者说是词的一个组合,文本中每个词的出现都是独立的,不依赖于其他词是否出现,或者说当这篇文章的作者在任意一个位置选择一个词汇都不受前面句子的影响而独立选择的。
研表究明,汉字序顺并不定一影阅响读。比如当你看完这句话后,才发这现里的字全是都乱的。
具体原理可以参考我以前写的朴素贝叶斯算法里的词袋模型:机器学习_5:朴素贝叶斯算法
简单来说,词袋模型抛弃了词与词之间的联系,将每个词单独进行比较,比如如果两个文档具有相似的内容,那么它们就是相似的,最典型的例子就是回文,比如信言不美,美言不信,读起来意思不一样,但如果是词袋检测的话会认为这两句话是同一个句子。
2.Bag of features原理: 图像特征词典
2.1.特征提取
和以前的特征提取一样,我们使用SIFT算法提取特征点,假设我们每张图像提取的特征点数目是固定的100个(实际上每幅图像能提取的特征点数量不同且远远大于100个),假设有100张图片(实际图片数目远比这个多),那么我们一共可以收集到1万个特征点。如果我们直接用这1万个特征点作为视觉词典,针对输入特征集,根据视觉词典进行量化,把输入图像转化成视觉单词(visual words)的频率直方图。

如图所示,类似图像中的例子,但如果我们这1万个特征点都作为特征向量的话,每幅图像的频率直方图就会变得很宽,使用率才1/100。所以我们使用其他方法来将特征向量的数量减少。
2.2.K-means聚类算法



如图所示,每个特征点都有RGB三个像素通道,我们将这些特征点转换成RGB色彩空间中的立体点,然后随机设置k个聚类中心,最小化每个特征 xi 与其相对应的聚类中心 mk之间的欧式距离,最后将所有的特征点聚集成k个特征中心,这样我们就可以大幅度减少视觉词典内的特征数。

算法流程:
1.随机初始化 K 个聚类中
2.重复下述步骤直至算法收敛:
对应每个特征,根据距离关系赋值给某个中心/类别
对每个类别,根据其对应的特征集重新计算聚类中心
问题显而易见,k的取值是比较难以确定的,k值太少,视觉单词无法覆盖所有可能出现的情况,k值过大,计算量大,容易过拟合
2.3.图像检索
那么有了给定图像的bag-of-features直方图特征,应该如何实现图像分类/检索呢?
给定输入图像的BOW直方图, 在数据库中查找 k 个最近邻的图像,对于图像分类问题,可以根据这k个近邻图像的分类标签,投票获得分类结果,当训练数据足以表述所有图像的时候,检索/分类效果良好
3.代码实现
3.1训练视觉词典
import pickle
from PCV.imagesearch import vocabulary
from PCV.tools.imtools import get_imlist
from PCV.localdescriptors import sift
#获取图像列表
imlist = get_imlist("D:\ vscode\ python\ input\ image")
nbr_images = len(imlist)
print('nbr_images:',nbr_images)
#获取特征列表
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('Image')
voc.train(featlist, 200, 10)#调用了PCV的vocabulary.py中的train函数
#保存词汇
with open('D:\ vscode\ python\ input\ image\ vocabulary.pkl', 'wb') as f:
pickle.dump(voc, f)#将生成的词汇保存到vocabulary.pkl(f)中
print ('vocabulary is:', voc.name, voc.nbr_words)
python

3.2.构建索引
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
#获取图像列表
imlist = get_imlist("D:\ vscode\ python\ input\ image")
nbr_images = len(imlist)
#获取特征列表
featlist = [imlist[i][:-3]+'sift' for i in range(nbr_images)]
#载入词汇
with open('D:\ vscode\ python\ input\ image\ vocabulary.pkl', 'rb') as f:
voc = pickle.load(f)
#创建索引
indx = imagesearch.Indexer('testImaAdd.db',voc)
indx.create_tables()
#遍历所有的图像,并将它们的特征投影到词汇上
for i in range(nbr_images)[:110]:
locs,descr = sift.read_features_from_file(featlist[i])
indx.add_to_index(imlist[i],descr)
#提交到数据库
indx.db_commit()
con = sqlite.connect('testImaAdd.db')
print (con.execute('select count (filename) from imlist').fetchone())
print (con.execute('select * from imlist').fetchone())
python

3.3.检索图片
import pickle
from PCV.localdescriptors import sift
from PCV.imagesearch import imagesearch
from PCV.geometry import homography
from PCV.tools.imtools import get_imlist
#载入图像列表
imlist = get_imlist('D:\ vscode\ python\ input\ image')
nbr_images = len(imlist)
#载入特征列表
featlist = [imlist[i][:-3]+'sift' for i in range(nbr_images)]
#载入词汇
with open('D:\ vscode\ python\ input\ image\ vocabulary.pkl', 'rb') as f:
voc = pickle.load(f)
src = imagesearch.Searcher('testImaAdd.db',voc)
#查询图像索引和查询返回的图像数
q_ind = 1
nbr_results = 5
# 常规查询(按欧式距离对结果排序)
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[:5]) #常规查询
imagesearch.plot_results(src,res_geom[:5]) #重排后的结果
python

3.4.测试结果

4.总结
1.使用k-means聚类,除了其K和初始聚类中心选择的问题外,对于海量数据,输入矩阵的巨大将使得内存溢出及效率低下。
2.字典大小的选择也是问题,字典过大,单词缺乏一般性,对噪声敏感,计算量大,关键是图象投影后的维数高;字典太小,单词区分性能差,对相似的目标特征无法表示。
3.相似性测度函数用来将图象特征分类到单词本的对应单词上,其涉及线型核,塌方距离测度核,直方图交叉核等的选择。
