2.
1# -*- coding: UTF-8 -*-
2import numpy as np
3import h5py
4import matplotlib.image as mpimg
5import matplotlib.pyplot as plt
6from keras.applications.vgg16 import VGG16
7from keras.applications.vgg16 import preprocess_input as preprocess_input_vgg
8from keras.preprocessing import image
9
10class VGGNet:
11 def __init__(self):
12 self.input_shape = (224, 224, 3)
13 self.weight = 'imagenet' # None代表随机初始化,即不加载预训练权重
14 self.pooling = 'max' # avg
15 del_vgg = VGG16(weights=self.weight,
16 input_shape=(self.input_shape[0], self.input_shape[1], self.input_shape[2]),
17 pooling=self.pooling,
18 include_top=False)
19 # del_vgg.s((1, 224, 224, 3)))
20
21 # 提取vgg16最后⼀层卷积特征( Use vgg16/Resnet model to extract features Output normalized feature vector)
22 def vgg_extract_feat(self, img_path):
23 img = image.load_img(img_path, target_size=(self.input_shape[0], self.input_shape[1]))
24 img = image.img_to_array(img)
25 img = np.expand_dims(img, axis=0)
26 img = preprocess_input_vgg(img)
27 feat = del_vgg.predict(img)
28 # print(feat.shape)
29 norm_feat = feat[0] / (feat[0])
捍卫阳光30 return norm_feat
1def get_score(image_path='22.png'):
2 # read in indexed images' feature vectors and corresponding image names
3 index = 'vgg_featureCNN.h5'
4 h5f = h5py.File(index, 'r')
5 feats = h5f['dataset_1'][:]
现代优化计算方法
6 imgNames = h5f['dataset_2'][:]
7 h5f.close()
8
9 # init VGGNet16 model
10 model = VGGNet()
11
12 # extract query image's feature, compute simlarity score and sort
13 queryVec = model.vgg_extract_feat(image_path) # 修改此处改变提取特征的⽹络
14 scores = np.dot(queryVec, feats.T)
15 # scores = np.dot(queryVec, feats.T)/((queryVec)*(feats.T))
16 rank_ID = np.argsort(scores)[::-1]
17 rank_score = scores[rank_ID]
18 print (rank_ID)
19 print(rank_score)俄罗斯和叙利亚的关系>中国工程物理研究院
20
21 # number of top retrieved images to show
22 maxres = 3 # 检索出三张相似度最⾼的图⽚
23 imlist = []
24 for i, index in enumerate(rank_ID[0:maxres]):
25 imlist.append(imgNames[index])
26
27 top_1_score = str(rank_score[0]).strip()
隧道塌方处理
方案28 top_1_md5 = str(imlist[0]).split(".")[0].split("'")[1].strip()
29
30 # print("image names: " + str(imgNames[index]) + " scores: %f" % rank_score[i])
大稿国际艺术区31 # print("top %d images in order are: " % maxres, imlist)
32 # # show top #maxres retrieved result one by one
33 # for i, im in enumerate(imlist):
34 # image = mpimg.imread('database/' + str(im, 'utf-8'))
35 # plt.title("search output %d" % (i + 1))
36 # plt.imshow(image)
37 # plt.show()
38
39 return [top_1_md5, top_1_score]