您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“Python人工智能實(shí)戰(zhàn)之以圖搜圖怎么實(shí)現(xiàn)”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
給出一張圖像后,在整個(gè)數(shù)據(jù)集中(至少100個(gè)樣本)找到與這張圖像相似的圖像(至少5張),并把圖像有順序的展示。
解釋器:python3.10
編譯器:Pycharm
必用配置包:
numpy、h6py、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 h6py 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:\pythonProject5\flower_roses' index = 'vgg_featureCNN.h6' 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) # 修改此處改變提取特征的網(wǎng)絡(luò) 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 ...") h6f = h6py.File(output, 'w') h6f.create_dataset('dataset_1', data=feats) # h6f.create_dataset('dataset_2', data = names) h6f.create_dataset('dataset_2', data=np.string_(names)) h6f.close()
# -*- coding: utf-8 -*- from vgg import VGGNet import numpy as np import h6py import matplotlib.pyplot as plt import matplotlib.image as mpimg import argparse query = r'D:\pythonProject5\rose\red_rose.jpg' index = 'vgg_featureCNN.h6' result = r'D:\pythonProject5\flower_roses' # read in indexed images' feature vectors and corresponding image names h6f = h6py.File(index, 'r') # feats = h6f['dataset_1'][:] feats = h6f['dataset_1'][:] print(feats) imgNames = h6f['dataset_2'][:] print(imgNames) h6f.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) # 修改此處改變提取特征的網(wǎng)絡(luò) 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() # 獲取當(dāng)前圖像 f.savefig(r'D:\pythonProject5\result\{}.jpg'.format(i),dpi=100) #f.clear() # 釋放內(nèi)存 plt.show()
數(shù)據(jù)集
結(jié)果(運(yùn)行前)
原圖
分享一個(gè)實(shí)用又簡(jiǎn)單的爬蟲(chóng)代碼,搜圖頂呱呱!
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('你想要下載什么圖片?請(qǐng)輸入:') epoch = input('你想要下載幾輪圖片?請(qǐng)輸入(一輪為60張左右圖片):') # 需要迭代幾次圖片 imgdata_set(save_path, word, epoch)
“Python人工智能實(shí)戰(zhàn)之以圖搜圖怎么實(shí)現(xiàn)”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。