最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python人工智能實戰(zhàn)之以圖搜圖的實現(xiàn)

 更新時間:2022年05月13日 16:08:56   作者:代碼騎士  
這篇文章主要為大家詳細(xì)介紹了如何基于vgg網(wǎng)絡(luò)和Keras深度學(xué)習(xí)框架實現(xiàn)以圖搜圖功能。文中的示例代碼講解詳細(xì),感興趣的小伙伴可以學(xué)習(xí)一下

前言

基于vgg網(wǎng)絡(luò)和Keras深度學(xué)習(xí)框架的以圖搜圖功能實現(xiàn)。

一、實驗要求

給出一張圖像后,在整個數(shù)據(jù)集中(至少100個樣本)找到與這張圖像相似的圖像(至少5張),并把圖像有順序的展示。

二、環(huán)境配置

解釋器:python3.10

編譯器:Pycharm

必用配置包:

numpy、h5py、matplotlib、keras、pillow

三、代碼文件

1、vgg.py

# -*- 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

2、index.py

# -*- 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:\pythonProject5\flower_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)  # 修改此處改變提取特征的網(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 ...")
 
    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()

3、test.py

# -*- 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:\pythonProject5\rose\red_rose.jpg'
index = 'vgg_featureCNN.h5'
result = r'D:\pythonProject5\flower_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)  # 修改此處改變提取特征的網(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()

四、演示

1、項目文件夾

數(shù)據(jù)集

結(jié)果(運(yùn)行前)

原圖

2、相似度排序輸出

3、保存結(jié)果

五、尾聲

分享一個實用又簡單的爬蟲代碼,搜圖頂呱呱!

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)

到此這篇關(guān)于Python人工智能實戰(zhàn)之以圖搜圖的實現(xiàn)的文章就介紹到這了,更多相關(guān)Python以圖搜圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 如何Tkinter模塊編寫Python圖形界面

    如何Tkinter模塊編寫Python圖形界面

    本文講解為何使用Tkinter而非PyQt,創(chuàng)建一個基本的Tkinter程序,模塊化Tkinter程序,希望對大家有幫助。
    2020-10-10
  • python 多進(jìn)程并行編程 ProcessPoolExecutor的實現(xiàn)

    python 多進(jìn)程并行編程 ProcessPoolExecutor的實現(xiàn)

    這篇文章主要介紹了python 多進(jìn)程并行編程 ProcessPoolExecutor的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-10-10
  • 深入理解python中的淺拷貝和深拷貝

    深入理解python中的淺拷貝和深拷貝

    下面小編就為大家?guī)硪黄钊肜斫鈖ython中的淺拷貝和深拷貝。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-05-05
  • python數(shù)據(jù)結(jié)構(gòu)之圖的實現(xiàn)方法

    python數(shù)據(jù)結(jié)構(gòu)之圖的實現(xiàn)方法

    這篇文章主要介紹了python數(shù)據(jù)結(jié)構(gòu)之圖的實現(xiàn)方法,實例分析了Python圖的表示方法與常用尋路算法的實現(xiàn)技巧,需要的朋友可以參考下
    2015-07-07
  • Python 虛擬空間的使用代碼詳解

    Python 虛擬空間的使用代碼詳解

    這篇文章主要介紹了Python 虛擬空間的使用,本文通過示例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-06-06
  • Python查找多個字典公共鍵key的方法

    Python查找多個字典公共鍵key的方法

    這篇文章主要介紹了Python查找多個字典公共鍵key案例,文章主要通過案例分享展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-04-04
  • drf序列化器serializer的具體使用

    drf序列化器serializer的具體使用

    本文主要介紹了drf序列化器serializer的具體使用,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-07-07
  • Python繪制七彩花朵(用Turtle)

    Python繪制七彩花朵(用Turtle)

    這篇文章主要給大家介紹了關(guān)于Python使用Turtle繪制七彩花朵的相關(guān)資料,通過本文介紹的方法就算剛?cè)腴T的朋友也可以很快的入手繪制出漂亮的七彩花朵,需要的朋友可以參考下
    2023-07-07
  • Python機(jī)器學(xué)習(xí)實戰(zhàn)之k-近鄰算法的實現(xiàn)

    Python機(jī)器學(xué)習(xí)實戰(zhàn)之k-近鄰算法的實現(xiàn)

    k-近鄰算法采用測量不同特征值之間的距離方法進(jìn)行分類。這篇文章主要為大家介紹了如何通過python實現(xiàn)K近鄰算法,有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2021-11-11
  • python2和python3實現(xiàn)在圖片上加漢字的方法

    python2和python3實現(xiàn)在圖片上加漢字的方法

    python2和python3實現(xiàn)在圖片上加漢字,最主要的區(qū)別還是內(nèi)部編碼方式不一樣導(dǎo)致的,在代碼上表現(xiàn)為些許的差別。這篇文章主要介紹了python2和python3實現(xiàn)在圖片上加漢字,需要的朋友可以參考下
    2019-08-08

最新評論

美姑县| 麦盖提县| 赣州市| 民勤县| 景宁| 大渡口区| 新邵县| 临高县| 尚义县| 米脂县| 松阳县| 商城县| 香格里拉县| 青田县| 普陀区| 钦州市| 平原县| 木里| 咸丰县| 县级市| 白银市| 观塘区| 扬州市| 吉首市| 昌邑市| 深泽县| 股票| 陇南市| 深圳市| 于田县| 定远县| 咸阳市| 大厂| 当涂县| 郴州市| 林周县| 介休市| 丹凤县| 浙江省| 化隆| 郯城县|