BOW也就是Bag-of-Words,此模型源于文本分类技术。在信息检索中,它假定对于一个文本,忽略其词序、语法和句法,将其仅仅看作是一个词集合,或者说是词的一个组合。文本中每个词的出现都是独立的,不依赖于其他词是否出现,或者说这篇文章的作者在任意一个位置选择词汇都不受前面句子的影响而独立选择的。之后更多的研究者归结此方法为Bag-of-Features,并用于图像分类、目标识别和图像检索。Bag-of-Features模型仿照文本检索领域的Bag-of-Words方法,把每幅图像描述为一个局部区域或关键点(Patches/Key Points)特征的无序集合,每个特征点可以看成一个视觉单词,所有这些视觉单词构成的集合称为视觉词汇,有时也称为视觉码本。这样,就能够把文本检索及分类的方法用到图像分类及检索中去。
运用sift算子提取图像特征。
将所有图像的所有SIFT特征点放在一起,进行聚类,得出的聚类中心便是视觉词汇(Visual vocabulary)。所有视觉词汇的集合便是视觉词典。聚类中心的大小可以设置,本实验采用的是K-Means聚类算法。
K-Means算法流程:
对于输入的特征(128维向量),将该特征映射到距离其最近的视觉单词,并实现计数,统计出词频直方图
在文本检索中,不同的单词对文本检索的贡献有差异。运用到图像检索中也是同样的道理,每张图片都具有的共性特征的权重应该被降低。
投票值的大小也就是直方图上柱体的高度。
倒排法也就是特征到图像的映射关系。
举例解释:
Cn为特征点,In为输入的图像
C1:{I1,I101}表示特征点在I1和I101这两幅图像上出现,以下同理
C2:{I2,I99}
C3:{I1,I5,I100}
C4:{I1,I101,I3}
特征点C1与I1,I101有关,特征点C2与I2,I99有关,特征点C3与I1,I5,I100有关,特征点C4与I1,I101,I3有关。由此锁定I1,I3,I5,I100,I101这些图像,再进一步,I1和I101出现两次,那么就锁定这两幅图像来匹配特征。
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('test1/')
nbr_images = len(imlist)
#获取特征列表
featlist = [imlist[i][:-3]+'sift' for i in range(nbr_images)]
# load vocabulary
#载入词汇
with open('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)[:888]:
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())
把图像特征投影到词汇上,用的是之前已经保存好的词汇。(创建词汇的代码后面会介绍)
结果:
文件夹中会出现
import pickle
from PCV.imagesearch import vocabulary
from PCV.tools.imtools import get_imlist
from PCV.localdescriptors import sift
#获取图像列表
imlist = get_imlist('test1/')
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, 888, 10)
#保存词汇
# saving vocabulary
with open('test1/vocabulary.pkl', 'wb') as f:
pickle.dump(voc, f)
print ('vocabulary is:', voc.name, voc.nbr_words)
上面便是创建词汇的代码。
运行成功之后文件夹中会出现
这个文件是用来保存生成的词汇。
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('test1/')
nbr_images = len(imlist)
#获取特征列表
featlist = [imlist[i][:-3]+'sift' for i in range(nbr_images)]
#载入词汇
f = open('test1/vocabulary.pkl', 'rb')
voc = pickle.load(f)
f.close()
src = imagesearch.Searcher('testImaAdd.db',voc)
locs,descr = sift.read_features_from_file(featlist[0])
iw = voc.project(descr)
print ('ask using a histogram...')
print (src.candidates_from_histogram(iw)[:10])
src = imagesearch.Searcher('testImaAdd.db',voc)
print ('try a query...')
nbr_results = 12
res = [w[1] for w in src.query(imlist[0])[:nbr_results]]
imagesearch.plot_results(src,res)
上面的代码能够利用建立起来的索引找到包含特定单词的所有图像
运行结果为
查找出来的这些候选图像都是不准确的。所以,接下来,要取出该列表中任意数量的元素并比较他们的直方图,这样会极大地提高检索效率。
import cherrypy
import pickle
import urllib
import os
from numpy import *
#from PCV.tools.imtools import get_imlist
from PCV.imagesearch import imagesearch
import random
class SearchDemo:
def __init__(self):
# 载入图像列表
self.path = 'test1/'
#self.path = 'D:/python_web/isoutu/first500/'
self.imlist = [os.path.join(self.path,f) for f in os.listdir(self.path) if f.endswith('.jpg')]
#self.imlist = get_imlist('./first500/')
#self.imlist = get_imlist('E:/python/isoutu/first500/')
self.nbr_images = len(self.imlist)
print (self.imlist)
print (self.nbr_images)
self.ndx = list(range(self.nbr_images))
print (self.ndx)
# 载入词汇
# f = open('first1000/vocabulary.pkl', 'rb')
with open('test1/vocabulary.pkl','rb') as f:
self.voc = pickle.load(f)
#f.close()
# 显示搜索返回的图像数
self.maxres = 10
def index(self, query=None):
self.src = imagesearch.Searcher('testImaAdd.db', self.voc)
if query:
# query the database and get top images
#查询数据库,并获取前面的图像
res = self.src.query(query)[:self.maxres]
for dist, ndx in res:
imname = self.src.get_filename(ndx)
html += ""
html += "
"
print (imname+"################")
html += ""
# show random selection if no query
# 如果没有查询图像则随机显示一些图像
else:
random.shuffle(self.ndx)
for i in self.ndx[:self.maxres]:
imname = self.imlist[i]
html += ""
html += "
"
print (imname+"################")
html += ""
html += self.footer
return html
index.exposed = True
cherrypy.quickstart(SearchDemo(), '/', config=os.path.join(os.path.dirname('__file__'), 'service.conf'))
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('test1/')
nbr_images = len(imlist)
#载入特征列表
featlist = [imlist[i][:-3]+'sift' for i in range(nbr_images)]
#载入词汇
with open('test1/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]) #重排后的结果