2021-06-06

Posted 差不多女生

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2021-06-06相关的知识,希望对你有一定的参考价值。

计算机视觉——图像检索

图像检索

图像检索原理

图像检索,简单的说,便是从图片检索数据库中检索出满足条件的图片,图像检索技术的研究根据描述图像内容方式的不同可以分为两类:基于文本的图像检索技术(TBIR),基于内容的图像检索技术(CBIR),但是我们目前主要学习基于内容的图像检索技术。
**基于内容的图像检索技术(CBIR):**用于检索在视觉上具有相似性的图像。这样返回的图像可以是颜色相似、纹理相同、图像中物体或场景相似,基本上都是这些图像自身共有的任何信息。

基于BOW的图像检索原理

BOW模型:
从一个集提取特征描述子,利用一些聚类算法可以构建出视觉单词。视觉单词并不高端,只是在给定特征描述子空间中的一组向量集,在聚类时得到的视觉单词是聚类质心。用视觉单词直方图来表示图像,则该模型便成为BOW模型。

K-means聚类算法
聚类(Clustering)是一种无监督学习算法,其目的是将数据集中的样本划分为若干个不相交的子集,每个子集称为一个簇(Cluster)。聚类的时候并不关心某一类是什么,只根据数据的相似性,将数据划分到不同的组中。每个组内的成员具有相似的性质。
创建词汇步骤:
1.特征提取
2.学习“视觉词典”
3.针对输入的特征集,根据视觉词典进行量化
4.把输入图像转化为视觉单词的频率直方图
BOF(Bag of features):
BoF(Bag Of Feature)借鉴文本处理的词袋(BoW,Bag Of Bag)算法,将图像表示成视觉关键词的统计直方图。提取词汇表,这里关键是得到图像库的“词汇表”。为了得到图像库的“词汇表",通常对提取到的图像特征进行聚类,得到一定个数的簇。这些聚类得到的簇,就是图像的”词汇“,可以称为视觉词(Visual Word)。聚类形成的簇,可以使用聚类中心来描述,所以,视觉词指的是图像的局部区域特征(如纹理,特征点)经过聚类形成的聚类中心。Bag-of-Features更多地是用于图像分类或对象识别。在上述思路下对训练集提取Bag-of-Features特征,在某种监督学习(如:SVM)的策略下,对训练集的Bag-of-Features特征向量进行训练,获得对象或场景的分类模型;对于待测图像,提取局部特征,计算局部特征与词典中每个码字的特征距离,选取最近距离的码字代表该特征,建立一个统计直方图,统计属于每个码字的特征个数,即为待测图像之Bag-of-Features特征;在分类模型下,对该特征进行预测从实现对待测图像的分类
基于SIFT特征构建BoF的步骤
1、SIFT特征提取 :提取训练集中所有图像的SIFT特征,设有MM幅图像,共得到NN个SIFT特征。
2、构建视觉词汇表 对提取到的NN个SIFT特征进行聚类,得到KK个聚类中心,组成图像的视觉词汇表。
3、图像的视觉词向量表示,统计每幅图像中视觉词汇的出现的次数,得到图像的特征向量。在检索时,该特征向量就代表该幅图像。统计时,计算图像中提取到的SIFT特征点到各个视觉词(聚类中心)的距离,将其归类到聚类最近的视觉词中。

代码及实现过程

提取图像库中图像的局部特征,提取图像的sift特征并构建图像库的视觉词典:

# -*- coding: utf-8 -*-
import pickle
from PCV.imagesearch import vocabulary
from PCV.tools.imtools import get_imlist
import sift

# 获取图像列表
# imlist = get_imlist('E:/Python37_course/test7/first1000/')
imlist = get_imlist('./data/')
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)
voc = vocabulary.Vocabulary('bow')
voc.train(featlist, 150, 10)

# 保存词汇
# saving vocabulary
# with open('E:/Python37_course/test7/first1000/vocabulary.pkl', 'wb') as f:
#     pickle.dump(voc, f)

with open('./data/vocabulary.pkl', 'wb') as f:
    pickle.dump(voc, f)
print('vocabulary is:', voc.name, voc.nbr_words)

将模型数据导入数据库

import pickle
from PCV.tools.imtools import get_imlist
from PCV.localdescriptors import sift
from PCV.imagesearch import imagesearch
from sqlite3 import dbapi2 as sqlite # 使用sqlite作为数据库


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

# load vocabulary
#载入词汇
with open('./data/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())

测试

import pickle
from PCV.tools.imtools import get_imlist
from PCV.localdescriptors import sift
from PCV.imagesearch import imagesearch
from PCV.geometry import homography

"""
#获取图像列表
imlist = get_imlist('C:/Users/86158/Desktop/COMPUTERVISION/BagOfFeature/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)
#保存词汇
# saving vocabulary
with open('C:/Users/86158/Desktop/COMPUTERVISION/BagOfFeature/BOW/vocabulary.pkl', 'wb') as f:
    pickle.dump(voc, f)
print ('vocabulary is:', voc.name, voc.nbr_words)
"""

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

# load vocabulary
#载入词汇
with open('C:/Users/86158/Desktop/COMPUTERVISION/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)[: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())
"""

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

#载入词汇
f = open('C:/Users/Desktop/BOW/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)
"""


# load image list and vocabulary
#载入图像列表
imlist = get_imlist('./data/')
nbr_images = len(imlist)
#载入特征列表
featlist = [imlist[i][:-3]+'sift' for i in range(nbr_images)]

#载入词汇
with open('./data/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 = 6
nbr_results = 4

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

结果:

总结:
因为 K-Means算法是原型聚类的一种,对于给定的样本集,按照样本之间的距离大小,将样本集划分为K个簇。让簇内的点尽量紧密的连在一起,而让簇间的距离尽量大。所以k-means聚类,除了其K和初始聚类中心选择的问题外,对于海量数据,输入矩阵的巨大将使得内存溢出及效率低下。当创建的字典太小时,单词区分性能差,对相似的目标特征无法表示。

以上是关于2021-06-06的主要内容,如果未能解决你的问题,请参考以下文章

2021-06-06

2021-06-06

《安富莱嵌入式周报》第215期:2021.05.31--2021.06.06

2021-06-06

2021-06-06

2021-06-06