<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
基于vgg网路和Keras深度学习框架的以图搜图功能实现。
给出一张影象后,在整个资料集中(至少100个样本)找到与这张影象相似的影象(至少5张),并把影象有顺序的展示。
直译器:python3.10
编译器:Pycharm
必用设定包:
numpy、h5py、matplotlib、keras、pillow
# -*- coding: utf-8 -*- import numpy as np from numpy import linalg as LA from keras.applications.vgg16 import VGG16 from keras.preprocessing import image from keras.applications.vgg16 import preprocess_input as preprocess_input_vgg class VGGNet: def __init__(self): self.input_shape = (224, 224, 3) self.weight = 'imagenet' self.pooling = 'max' 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) self.model_vgg.predict(np.zeros((1, 224, 224 , 3))) #提取vgg16最后一层折积特征 def vgg_extract_feat(self, img_path): img = image.load_img(img_path, target_size=(self.input_shape[0], self.input_shape[1])) img = image.img_to_array(img) img = np.expand_dims(img, axis=0) img = preprocess_input_vgg(img) feat = self.model_vgg.predict(img) # print(feat.shape) norm_feat = feat[0]/LA.norm(feat[0]) return norm_feat
# -*- coding: utf-8 -*- import os import h5py import numpy as np import argparse from vgg import VGGNet def get_imlist(path): return [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.jpg')] if __name__ == "__main__": database = r'D:pythonProject5flower_roses' index = 'vgg_featureCNN.h5' img_list = get_imlist(database) print(" feature extraction starts") feats = [] names = [] model = VGGNet() for i, img_path in enumerate(img_list): norm_feat = model.vgg_extract_feat(img_path) # 修改此处改变提取特征的网路 img_name = os.path.split(img_path)[1] feats.append(norm_feat) names.append(img_name) print("extracting feature from image No. %d , %d images in total" % ((i + 1), len(img_list))) feats = np.array(feats) output = index print(" writing feature extraction results ...") h5f = h5py.File(output, 'w') h5f.create_dataset('dataset_1', data=feats) # h5f.create_dataset('dataset_2', data = names) h5f.create_dataset('dataset_2', data=np.string_(names)) h5f.close()
# -*- coding: utf-8 -*- from vgg import VGGNet import numpy as np import h5py import matplotlib.pyplot as plt import matplotlib.image as mpimg import argparse query = r'D:pythonProject5rosered_rose.jpg' index = 'vgg_featureCNN.h5' result = r'D:pythonProject5flower_roses' # read in indexed images' feature vectors and corresponding image names h5f = h5py.File(index, 'r') # feats = h5f['dataset_1'][:] feats = h5f['dataset_1'][:] print(feats) imgNames = h5f['dataset_2'][:] print(imgNames) h5f.close() print(" searching starts") queryImg = mpimg.imread(query) plt.title("Query Image") plt.imshow(queryImg) plt.show() # init VGGNet16 model model = VGGNet() # extract query image's feature, compute simlarity score and sort queryVec = model.vgg_extract_feat(query) # 修改此处改变提取特征的网路 print(queryVec.shape) print(feats.shape) scores = np.dot(queryVec, feats.T) rank_ID = np.argsort(scores)[::-1] rank_score = scores[rank_ID] # print (rank_ID) print(rank_score) # number of top retrieved images to show maxres = 6 # 检索出6张相似度最高的图片 imlist = [] for i, index in enumerate(rank_ID[0:maxres]): imlist.append(imgNames[index]) print(type(imgNames[index])) print("image names: " + str(imgNames[index]) + " scores: %f" % rank_score[i]) print("top %d images in order are: " % maxres, imlist) # show top #maxres retrieved result one by one for i, im in enumerate(imlist): image = mpimg.imread(result + "/" + str(im, 'utf-8')) plt.title("search output %d" % (i + 1)) plt.imshow(np.uint8(image)) f = plt.gcf() # 获取当前影象 f.savefig(r'D:pythonProject5result{}.jpg'.format(i),dpi=100) #f.clear() # 释放记忆体 plt.show()
资料集
结果(执行前)
原图
分享一个实用又简单的爬虫程式码,搜图顶呱呱!
import os import time import requests import re def imgdata_set(save_path,word,epoch): q=0 #停止爬取图片条件 a=0 #图片名称 while(True): time.sleep(1) 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) #word=需要搜寻的名字 headers={ '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' } response=requests.get(url,headers=headers) # print(response.request.headers) html=response.text # print(html) urls=re.findall('"objURL":"(.*?)"',html) # print(urls) for url in urls: print(a) #图片的名字 response = requests.get(url, headers=headers) image=response.content with open(os.path.join(save_path,"{}.jpg".format(a)),'wb') as f: f.write(image) a=a+1 q=q+20 if (q/20)>=int(epoch): break if __name__=="__main__": save_path = input('你想储存的路径:') word = input('你想要下载什么图片?请输入:') epoch = input('你想要下载几轮图片?请输入(一轮为60张左右图片):') # 需要迭代几次图片 imgdata_set(save_path, word, epoch)
到此这篇关于Python人工智慧实战之以图搜图的实现的文章就介绍到这了,更多相关Python以图搜图内容请搜寻it145.com以前的文章或继续浏览下面的相关文章希望大家以后多多支援it145.com!
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45