pythonコンテンツベースの画像検索(CBIR)
5774 ワード
始める前にまずいくつかのpythonサードパーティ製ライブラリパッケージをインストールします:pyQt 5、cherrypy、pysqlite(私はpython 3.7インストールのpysqlite 3です)PCVファイルパッケージとvlfeatを作業ディレクトリの下に置いて、siftファイルを構成します1、原理紹介:コンテンツベースの画像検索(CBIR)は根拠画像の色、テクスチャ、形状などの視覚的特徴を指します.特定のフィーチャーを含む画像を特定のライブラリで検索します.画像理解技術を融合させ、画像を入力すると同時に対応する特徴ベクトルも特徴ライブラリに格納する.画像検索を行う場合、所与のキーマップ毎に画像解析を行い、画像の特徴ベクトルを抽出する.この画像の特徴ベクトルと特徴ライブラリ内の特徴ベクトルをマッチングし,類似距離の大きさに応じて画像ライブラリ内を検索すれば必要な検索図が得られる.その重要な技術は画像特徴抽出と特徴マッチングにある.二、方法分類:1、SIFT特徴に基づく方法(本論文で採用)2、CNNに基づく方法三、基本手順:1.画像データベース2を作成する.入力画像を分析し、分類して統一的にモデリングする.各種画像モデルに基づいて画像特徴を抽出する特徴ライブラリに格納し、同時に特徴ライブラリにインデックス4を作成する.条件に基づいてテスト画像4、コード実装:1.画像の追加
2.語彙の作成
3.画像インデックス
4.モデル
# -*- 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('first1000/')
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)[: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())
2.語彙の作成
# -*- 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('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('first1000/vocabulary.pkl', 'wb') as f:
pickle.dump(voc, f)
print ('vocabulary is:', voc.name, voc.nbr_words)
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.モデル
# -*- coding: utf-8 -*-
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
"""
This is the image search demo in Section 7.6.
"""
class SearchDemo:
def __init__(self):
#
self.path = 'first1000/'
#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('first1000/vocabulary.pkl','rb') as f:
self.voc = pickle.load(f)
#f.close()
#
self.maxres = 10
# header and footer html
self.header = """
Image search
"""
self.footer = """