rubychiu/classify_image
0
1import gradio as gr2import os3import numpy as np4import pandas as pd5import matplotlib.pyplot as plt6 7from tensorflow.keras.applications import ResNet50V28from tensorflow.keras.models import Sequential, load_model9from tensorflow.keras.layers import Dense10from tensorflow.keras.utils import to_categorical11from tensorflow.keras.applications.resnet_v2 import preprocess_input12from tensorflow.keras.preprocessing.image import load_img, img_to_array13 14# 金門具有代表性的栗喉蜂虎、藍孔雀、戴勝、鱟及歐亞水獺五種物種。我們來挑戰五種類別總共用五十張照片, 看能不能打造一個神經網路學會辨識這五種類別。15# 讀入栗喉蜂虎、藍孔雀、戴勝、鱟及歐亞水獺資料圖檔16image_folders = ['Image01', 'Image02', 'Image03', 'Image04', 'Image05']17 18# 為了後面的需要,我們將五種類別照片的答案用 `labels` 呈現19labels = ["蘭嶼機場", "馬公機場", "飛機", "金門大橋", "尚義機場"]20 21num_classes = len(labels)22 23base_dir = './classify_image/'24 25# 載入並檢視訓練完成的模型。26model = load_model('my_cnn_model.h5') # Loading the Tensorflow Saved Model (PB)27print(model.summary())28 29# 注意現在主函數做辨識只有五個種類。而且是使用我們自行訓練的 model!30def classify_image(inp):31 inp = inp.reshape((-1, 256, 256, 3))32 inp = preprocess_input(inp)33 prediction = model.predict(inp).flatten()34 return {labels[i]: float(prediction[i]) for i in range(num_classes)}35 36image = gr.Image(shape=(256, 256), label="蘭嶼機場、馬公機場、飛機、金門大橋、尚義機場")37label = gr.Label(num_top_classes=num_classes, label="AI ResNet50V2遷移式學習辨識結果")38some_text="我能辨識蘭嶼機場、馬公機場、飛機、金門大橋、尚義機場。找張金門蘭嶼機場、馬公機場、飛機、金門大橋、尚義機場照片來考我吧!"39 40# 我們將金門栗喉蜂虎、藍孔雀、戴勝、鱟及歐亞水獺數據庫中的圖片拿出來當作範例圖片讓使用者使用41sample_images = []42for i in range(num_classes):43 thedir = base_dir + image_folders[i]44 for file in os.listdir(thedir):45 if file == ".git" or file == ".ipynb_checkpoints":46 continue47 sample_images.append(base_dir + image_folders[i] + '/' + file)48 49# 最後,將所有東西組裝在一起,就大功告成了!50iface = gr.Interface(fn=classify_image,51 inputs=image,52 outputs=label,53 title="AI 蘭嶼機場、馬公機場、飛機、金門大橋、尚義機場",54 description=some_text,55 examples=sample_images, live=True)56 57iface.launch()58 