Bag of features 图像特征词典原理及实现

一、(BOF)图像检索算法原理
BoW(Bag-of-Features)算法是由Csurka等在2004年提出并应用于图像处理领域的,该算法广泛应用于目标识别和图像检索。算法主要思想借鉴了文本检索的思想。在检索文本的过程中,文本由一系列的基本单元组成,这个单元通常是单词;同理,一副图像也可以看成是由一系列的基本单元组成,这些图像中的基本单元称为视觉单词(visual words)。
Bag of features 图像特征词典原理及实现_第1张图片

首先,我们用surf算法生成图像库中每幅图的特征点及描述符,再用k-means算法对图像库中的特征点进行训练,生成类心。生成每幅图像的BOF,具体方法为:判断图像的每个特征点与哪个类心最近,最近则放入该类心,最后将生成一列频数表,即初步的无权BOF。通过tf-idf对频数表加上权重,生成最终的bof。(因为每个类心对图像的影响不同。比如超市里条形码中的第一位总是6,它对辨别产品毫无作用,因此权重要减小)。对query进来的图像也进行3.4步操作,生成一列query图的BOF。将query的Bof向量与图像库中每幅图的Bof向量求夹角,夹角最小的即为匹配对象。

图像可以视为一种文档对象,图像中不同的局部区域或其特征可看做构成图像的词汇,其中相近的区域或其特征可以视作为一个词。这样,就能够把文本检索及分类的方法用到图像分类及检索中去。
Bag of features 图像特征词典原理及实现_第2张图片
1、局部特征提取:通过分割、密集或随机采集、关键点或稳定区域、显著区域等方式使图像形成不同的patches,并获得各patches处的特征。其中,SIFT特征较为流行。
Bag of features 图像特征词典原理及实现_第3张图片
2、构建视觉词典,由聚类中心代表的视觉词汇形成视觉词典。
Bag of features 图像特征词典原理及实现_第4张图片
3、生成码书,即构造Bag-of-Features特征,也即局部特征投影过程。
4、SVM训练BOF特征得分类模型,对待测图像BOF特征预测。

二、实现
1、视觉词典
1000个图片会生成sift文件后会生成一个视觉词典

# -*- 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]) #重排后的结果

4、运行结果
在这里插入图片描述
在这里插入图片描述
5、实验总结

你可能感兴趣的:(Bag of features 图像特征词典原理及实现)