其他分享
首页 > 其他分享> > 图像检索 Bag Of Features

图像检索 Bag Of Features

作者:互联网

BOF 图像检索


一、图像检索是什么?

CBIR(Content-Based Image Retrieval,基于内容的图像检索)技术用于检索在视觉上具相似性的图像。这样返回的图像可以是颜色相似、纹理相似、图像中的物体或场景相似;总之,基本上可以是这些图像自身共有的任何信息。
CBIR一般基于大型图像数据库实现。在建立图像数据库时,对输入的图像进行分析并分类统一建模, 然后根据图像模型提取图像特征存入特征库。而用户在通过接口设置查询条件时,可以采用一种或几种的特征组合来表示查询的图像, 然后,CBIR采用相似性匹配算法计算关键图像特征与特征库中图像特征的相似度,按照相似度从大到小的顺序将匹配图像反馈给用户。
时至今日,传统搜索引擎公司包括Google、百度、Bing都已提供一定的基于内容的图像搜索产品。如:Google Similar Images,百度识图。

二、BOF(Bag Of Feature)模型

BOF(Bag of Feature)模型是一种图像特征提取方法,它借鉴了文本分类BOW(Bag of Words)的思路,从图像抽象出很多具有代表性的「关键词」,形成一个字典,再统计每张图片中出现的「关键词」数量,得到图片的特征向量。

1.BOW

Bag of Words 是文本分类中一种通俗易懂的策略。一般来讲,对于一篇文档来说,如果我们要了解它的主要内容,最行之有效的策略是不考虑文档内的词的顺序关系和语法,抓取文本中的关键词,根据关键词出现的频率确定这段文本的中心思想。
比如:如果一则新闻中经常出现「iraq」、「terrorists」,那么,我们可以认为这则新闻应该跟伊拉克的恐怖主义有关。
bow
这里所说的关键词,就是Bag of words中的 words ,它们是区分度较高的单词(一般是地名人名等专有名词)。根据这些 words ,我们可以很快地识别出文章的内容,并快速地对文章进行分类。
根据这个思路,研究人员提出了Bag of Feature,在图像分类领域中,我们抽出的不再是一个个word,而是图像的关键特征Feature。

2.BOF

按照Bag of Feature算法的思想,首先我们要找到图像中的“关键词”,而这些“关键词”必须具备较高的区分度。在此过程中一般使用SIFT特征提取。
得到特征之后,我们会将这些特征通过聚类算法得出很多聚类中心。这些聚类中心通常具有较高的代表性,比如,对于人脸来说,虽然不同人的眼睛、鼻子等特征都不尽相同,但它们往往具有共性,而这些聚类中心就代表了这类共性。我们将这些聚类中心组合在一起放入“bag”中,形成一部字典(CodeBook)。
特征提取↓
在这里插入图片描述

3.BOF 算法过程

Bag of Feature 大概分为四步:

  1. 图像特征提取;
  2. 对特征进行聚类,得到一部字典( visual vocabulary );
  3. 根据字典将图片表示成向量(直方图);
  4. 训练分类器或者用 KNN 算法等进行检索

在这里插入图片描述

三、BOF实现

import pickle
from PCV.imagesearch import vocabulary
from PCV.tools.imtools import get_imlist
from PCV.localdescriptors import sift
from PCV.imagesearch import imagesearch
from PCV.geometry import homography
from sqlite3 import dbapi2 as sqlite


#获取图像列表
imlist = get_imlist('datasets/')
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) # 使用k-means算法在featurelist里边训练处一个词汇
                             # 注意这里使用了下采样的操作加快训练速度
                             # 将描述子投影到词汇上,以便创建直方图
#保存词汇
# saving vocabulary
with open('BOW/vocabulary.pkl', 'wb') as f:
    pickle.dump(voc, f)
print ('vocabulary is:', voc.name, voc.nbr_words)
import pickle
from PCV.imagesearch import vocabulary
from PCV.tools.imtools import get_imlist
from PCV.localdescriptors import sift
from PCV.imagesearch import imagesearch
from PCV.geometry import homography
from sqlite3 import dbapi2 as sqlite # 使用sqlite作为数据库


#获取图像列表
imlist = get_imlist('datasets/')
nbr_images = len(imlist)
#获取特征列表
featlist = [imlist[i][:-3]+'sift' for i in range(nbr_images)]

# load vocabulary
#载入词汇
with open('BOW/vocabulary.pkl', 'rb') as f:
    voc = pickle.load(f)
#创建索引
indx = imagesearch.Indexer('testImaAdd.db',voc) # 在Indexer这个类中创建表、索引,将图像数据写入数据库
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) # 使用add_to_index获取带有特征描述子的图像,投影到词汇上
                                       # 将图像的单词直方图编码存储
# 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())
# -*- 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('E:/Python37_course/test7/first1000/')
imlist = get_imlist('datasets/')
nbr_images = len(imlist)
#载入特征列表
featlist = [imlist[i][:-3]+'sift' for i in range(nbr_images)]

#载入词汇
'''with open('E:/Python37_course/test7/first1000/vocabulary.pkl', 'rb') as f:
    voc = pickle.load(f)'''
with open('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 = 2
nbr_results = 76

# 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[:6]) #常规查询
imagesearch.plot_results(src,res_geom[:6]) #重排后的结果


标签:检索,Features,vocabulary,PCV,Bag,sift,图像,import,imlist
来源: https://blog.csdn.net/Ohayo33/article/details/117620141