当前位置:   article > 正文

【机器学习应用】入门实验:基于vgg网络和Keras框架实现“以图搜图”

【机器学习应用】入门实验:基于vgg网络和Keras框架实现“以图搜图”

目录

前言:

一、实验要求:

二、环境配置:

三、代码文件:

1、vgg.py

2、index.py

3、test.py

四、演示:

1、项目文件夹

​ (1)数据集

 (2)结果(运行前)

 (3)原图

2、相似度排序输出

3、保存结果

五、尾声

 参考资料:


前言:

        基于vgg网络和Keras深度学习框架的以图搜图功能实现。

一、实验要求:

        给出一张图像后,在整个数据集中(至少100个样本)找到与这张图像相似的图像(至少5张),并把图像有顺序的展示。

二、环境配置

        解释器:python3.10

        编译器:Pycharm

        必用配置包:

numpy、h5py、matplotlib、keras、pillow

三、代码文件:

1、vgg.py

  1. # -*- coding: utf-8 -*-
  2. import numpy as np
  3. from numpy import linalg as LA
  4. from keras.applications.vgg16 import VGG16
  5. from keras.preprocessing import image
  6. from keras.applications.vgg16 import preprocess_input as preprocess_input_vgg
  7. class VGGNet:
  8. def __init__(self):
  9. self.input_shape = (224, 224, 3)
  10. self.weight = 'imagenet'
  11. self.pooling = 'max'
  12. self.model_vgg = VGG16(weights = self.weight, input_shape = (self.input_shape[0], self.input_shape[1], self.input_shape[2]), pooling = self.pooling, include_top = False)
  13. self.model_vgg.predict(np.zeros((1, 224, 224 , 3)))
  14. #提取vgg16最后一层卷积特征
  15. def vgg_extract_feat(self, img_path):
  16. img = image.load_img(img_path, target_size=(self.input_shape[0], self.input_shape[1]))
  17. img = image.img_to_array(img)
  18. img = np.expand_dims(img, axis=0)
  19. img = preprocess_input_vgg(img)
  20. feat = self.model_vgg.predict(img)
  21. # print(feat.shape)
  22. norm_feat = feat[0]/LA.norm(feat[0])
  23. return norm_feat

2、index.py

  1. # -*- coding: utf-8 -*-
  2. import os
  3. import h5py
  4. import numpy as np
  5. import argparse
  6. from vgg import VGGNet
  7. def get_imlist(path):
  8. return [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.jpg')]
  9. if __name__ == "__main__":
  10. database = r'D:\pythonProject5\flower_roses'
  11. index = 'vgg_featureCNN.h5'
  12. img_list = get_imlist(database)
  13. print(" feature extraction starts")
  14. feats = []
  15. names = []
  16. model = VGGNet()
  17. for i, img_path in enumerate(img_list):
  18. norm_feat = model.vgg_extract_feat(img_path) # 修改此处改变提取特征的网络
  19. img_name = os.path.split(img_path)[1]
  20. feats.append(norm_feat)
  21. names.append(img_name)
  22. print("extracting feature from image No. %d , %d images in total" % ((i + 1), len(img_list)))
  23. feats = np.array(feats)
  24. output = index
  25. print(" writing feature extraction results ...")
  26. h5f = h5py.File(output, 'w')
  27. h5f.create_dataset('dataset_1', data=feats)
  28. # h5f.create_dataset('dataset_2', data = names)
  29. h5f.create_dataset('dataset_2', data=np.string_(names))
  30. h5f.close()

3、test.py

  1. # -*- coding: utf-8 -*-
  2. from vgg import VGGNet
  3. import numpy as np
  4. import h5py
  5. import matplotlib.pyplot as plt
  6. import matplotlib.image as mpimg
  7. import argparse
  8. query = r'D:\pythonProject5\rose\red_rose.jpg'
  9. index = 'vgg_featureCNN.h5'
  10. result = r'D:\pythonProject5\flower_roses'
  11. # read in indexed images' feature vectors and corresponding image names
  12. h5f = h5py.File(index, 'r')
  13. # feats = h5f['dataset_1'][:]
  14. feats = h5f['dataset_1'][:]
  15. print(feats)
  16. imgNames = h5f['dataset_2'][:]
  17. print(imgNames)
  18. h5f.close()
  19. print(" searching starts")
  20. queryImg = mpimg.imread(query)
  21. plt.title("Query Image")
  22. plt.imshow(queryImg)
  23. plt.show()
  24. # init VGGNet16 model
  25. model = VGGNet()
  26. # extract query image's feature, compute simlarity score and sort
  27. queryVec = model.vgg_extract_feat(query) # 修改此处改变提取特征的网络
  28. print(queryVec.shape)
  29. print(feats.shape)
  30. scores = np.dot(queryVec, feats.T)
  31. rank_ID = np.argsort(scores)[::-1]
  32. rank_score = scores[rank_ID]
  33. # print (rank_ID)
  34. print(rank_score)
  35. # number of top retrieved images to show
  36. maxres = 6 # 检索出6张相似度最高的图片
  37. imlist = []
  38. for i, index in enumerate(rank_ID[0:maxres]):
  39. imlist.append(imgNames[index])
  40. print(type(imgNames[index]))
  41. print("image names: " + str(imgNames[index]) + " scores: %f" % rank_score[i])
  42. print("top %d images in order are: " % maxres, imlist)
  43. # show top #maxres retrieved result one by one
  44. for i, im in enumerate(imlist):
  45. image = mpimg.imread(result + "/" + str(im, 'utf-8'))
  46. plt.title("search output %d" % (i + 1))
  47. plt.imshow(np.uint8(image))
  48. f = plt.gcf() # 获取当前图像
  49. f.savefig(r'D:\pythonProject5\result\{}.jpg'.format(i),dpi=100)
  50. #f.clear() # 释放内存
  51. plt.show()

四、演示:

1、项目文件夹

 (1)数据集

 (2)结果(运行前)

 (3)原图

2、相似度排序输出

 

3、保存结果

五、尾声

        分享一个实用又简单的爬虫代码,搜图顶呱呱!

  1. import os
  2. import time
  3. import requests
  4. import re
  5. def imgdata_set(save_path,word,epoch):
  6. q=0 #停止爬取图片条件
  7. a=0 #图片名称
  8. while(True):
  9. time.sleep(1)
  10. url="https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word={}&pn={}&ct=&ic=0&lm=-1&width=0&height=0".format(word,q)
  11. #word=需要搜索的名字
  12. headers={
  13. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36 Edg/88.0.705.56'
  14. }
  15. response=requests.get(url,headers=headers)
  16. # print(response.request.headers)
  17. html=response.text
  18. # print(html)
  19. urls=re.findall('"objURL":"(.*?)"',html)
  20. # print(urls)
  21. for url in urls:
  22. print(a) #图片的名字
  23. response = requests.get(url, headers=headers)
  24. image=response.content
  25. with open(os.path.join(save_path,"{}.jpg".format(a)),'wb') as f:
  26. f.write(image)
  27. a=a+1
  28. q=q+20
  29. if (q/20)>=int(epoch):
  30. break
  31. if __name__=="__main__":
  32. save_path = input('你想保存的路径:')
  33. word = input('你想要下载什么图片?请输入:')
  34. epoch = input('你想要下载几轮图片?请输入(一轮为60张左右图片):') # 需要迭代几次图片
  35. imgdata_set(save_path, word, epoch)

 参考资料:

(2条消息) 基于深度学习实现以图搜图功能_chenghaoy的博客-CSDN博客_深度学习以图搜图icon-default.png?t=N7T8https://blog.csdn.net/chenghaoy/article/details/84977406(2条消息) pytorch——VGG网络搭建_heart_6662的博客-CSDN博客_pytorch 搭建vggicon-default.png?t=N7T8https://blog.csdn.net/qq_62932195/article/details/122416591

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/寸_铁/article/detail/880899
推荐阅读
相关标签
  

闽ICP备14008679号