提示:以下是本篇文章正文内容,案例可供参考
一、原理
Bag of Feature 是一种图像特征提取方法,它借鉴了文本分类的思路(Bag of Words),从图像抽象出很多具有代表性的「关键词」,形成一个字典,再统计每张图片中出现的「关键词」数量,得到图片的特征向量。
二、检索流程
- 特征提取
- 构建视觉词典
- 输入特征集根据视觉词典量化
- 输入图像转化成视觉单词的频率直方图
- 构造图像倒排表进行索引
- 根据索引结果进行匹配
三、实验过程
准备工作
先收集一定数量图片来构建数据库,这里文件夹使用了150+张图片
(图源网络)
代码
1.生成词汇表
# -*- coding: utf-8 -*-
import pickle
from pcv.imagesearch import vocabulary
from pcv.tools.imtools import get_imlist
from pcv.localdescriptors import sift
#获取图像列表
imlist = get_imlist('D:/JMU/PicVisual/BagOfFeature/pic')
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('D:/JMU/PicVisual/BagOfFeature/BOW/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
#获取图像列表
imlist = get_imlist('D:/JMU/PicVisual/BagOfFeature/pic/')
nbr_images = len(imlist)
#获取特征列表
featlist = [imlist[i][:-3]+'sift' for i in range(nbr_images)]
# load vocabulary
#载入词汇
with open('D:/JMU/PicVisual/BagOfFeature/BOW/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)[:500]:
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('D:/JMU/PicVisual/BagOfFeature/pic/')
nbr_images = len(imlist)
#载入特征列表
featlist = [imlist[i][:-3]+'sift' for i in range(nbr_images)]
#载入词汇
with open('D:/JMU/PicVisual/BagOfFeature/BOW/vocabulary.pkl', 'rb') as f:
voc = pickle.load(f)
src = imagesearch.Searcher('testImaAdd.db',voc)# Searcher类读入图像的单词直方图执行查询
# index of query image and number of results to return
#查询图像索引和查询返回的图像数
q_ind = 0
nbr_results = 10
# 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:]:
try:
locs,descr = sift.read_features_from_file(featlist[ndx])
except:
continue
#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[:11]) #常规查询
imagesearch.plot_results(src,res_geom[:11]) #重排后的结果
该处使用的url网络请求的数据。
## 实验结果
第1张为用于查询的图片,且为自己拍摄的图片加入图库,2~9张为搜索到的图片,第2、4、5成功匹配到了亭子的特征找到了相同的地点,第7张匹配到了部分亭子的特征,找到了一张相似的亭子,第3、6、8、10张匹配出的是嘉庚特色建筑,而第9张图是无相关性的一张图片
遇到的问题
- a bytes-like object is required, not ‘str’'
如果出现该报错,同样的进入imagesearch.py文件中的报错位置,将其中的str删除掉,因为 python3和Python2.7在套接字返回值解码上有区别,
- table imlist already exists
先把数据库db文件删除再运行代码