classify_image / app.py
ccwu0918's picture
Update app.py
08db411
raw
history blame contribute delete
No virus
2.65 kB
import gradio as gr
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from tensorflow.keras.applications import ResNet50V2
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.applications.resnet_v2 import preprocess_input
from tensorflow.keras.preprocessing.image import load_img, img_to_array
# ้‡‘้–€ๅ…ทๆœ‰ไปฃ่กจๆ€ง็š„ๆ —ๅ–‰่œ‚่™Žใ€่—ๅญ”้›€ใ€ๆˆดๅ‹ใ€้ฑŸๅŠๆญไบžๆฐด็บไบ”็จฎ็‰ฉ็จฎใ€‚ๆˆ‘ๅ€‘ไพ†ๆŒ‘ๆˆฐไบ”็จฎ้กžๅˆฅ็ธฝๅ…ฑ็”จไบ”ๅๅผต็…ง็‰‡, ็œ‹่ƒฝไธ่ƒฝๆ‰“้€ ไธ€ๅ€‹็ฅž็ถ“็ถฒ่ทฏๅญธๆœƒ่พจ่ญ˜้€™ไบ”็จฎ้กžๅˆฅใ€‚
# ่ฎ€ๅ…ฅๆ —ๅ–‰่œ‚่™Žใ€่—ๅญ”้›€ใ€ๆˆดๅ‹ใ€้ฑŸๅŠๆญไบžๆฐด็บ่ณ‡ๆ–™ๅœ–ๆช”
image_folders = ['Merops_philippinus', 'pavo_cristatus', 'Upupa_epops', 'King_Crab', 'otter']
# ็‚บไบ†ๅพŒ้ข็š„้œ€่ฆ๏ผŒๆˆ‘ๅ€‘ๅฐ‡ไบ”็จฎ้กžๅˆฅ็…ง็‰‡็š„็ญ”ๆกˆ็”จ `labels` ๅ‘ˆ็พ
labels = ["ๆ —ๅ–‰่œ‚่™Ž", "่—ๅญ”้›€", "ๆˆดๅ‹", "้ฑŸ", "ๆญไบžๆฐด็บ"]
num_classes = len(labels)
base_dir = './classify_image/'
# ่ผ‰ๅ…ฅไธฆๆชข่ฆ–่จ“็ทดๅฎŒๆˆ็š„ๆจกๅž‹ใ€‚
model = load_model('my_cnn_model.h5') # Loading the Tensorflow Saved Model (PB)
print(model.summary())
# ๆณจๆ„็พๅœจไธปๅ‡ฝๆ•ธๅš่พจ่ญ˜ๅชๆœ‰ไบ”ๅ€‹็จฎ้กžใ€‚่€Œไธ”ๆ˜ฏไฝฟ็”จๆˆ‘ๅ€‘่‡ช่กŒ่จ“็ทด็š„ model!
def classify_image(inp):
inp = inp.reshape((-1, 256, 256, 3))
inp = preprocess_input(inp)
prediction = model.predict(inp).flatten()
return {labels[i]: float(prediction[i]) for i in range(num_classes)}
image = gr.Image(shape=(256, 256), label="ๆ —ๅ–‰่œ‚่™Žใ€่—ๅญ”้›€ใ€ๆˆดๅ‹ใ€้ฑŸๅŠๆญไบžๆฐด็บ็…ง็‰‡")
label = gr.Label(num_top_classes=num_classes, label="AI ResNet50V2้ท็งปๅผๅญธ็ฟ’่พจ่ญ˜็ตๆžœ")
some_text="ๆˆ‘่ƒฝ่พจ่ญ˜้‡‘้–€ๆ —ๅ–‰่œ‚่™Žใ€่—ๅญ”้›€ใ€ๆˆดๅ‹ใ€้ฑŸๅŠๆญไบžๆฐด็บใ€‚ๆ‰พๅผต้‡‘้–€ๆ —ๅ–‰่œ‚่™Žใ€่—ๅญ”้›€ใ€ๆˆดๅ‹ใ€้ฑŸๅŠๆญไบžๆฐด็บ็…ง็‰‡ไพ†่€ƒๆˆ‘ๅง!"
# ๆˆ‘ๅ€‘ๅฐ‡้‡‘้–€ๆ —ๅ–‰่œ‚่™Žใ€่—ๅญ”้›€ใ€ๆˆดๅ‹ใ€้ฑŸๅŠๆญไบžๆฐด็บๆ•ธๆ“šๅบซไธญ็š„ๅœ–็‰‡ๆ‹ฟๅ‡บไพ†็•ถไฝœ็ฏ„ไพ‹ๅœ–็‰‡่ฎ“ไฝฟ็”จ่€…ไฝฟ็”จ
sample_images = []
for i in range(num_classes):
thedir = base_dir + image_folders[i]
for file in os.listdir(thedir):
if file == ".git" or file == ".ipynb_checkpoints":
continue
sample_images.append(base_dir + image_folders[i] + '/' + file)
# ๆœ€ๅพŒ๏ผŒๅฐ‡ๆ‰€ๆœ‰ๆฑ่ฅฟ็ต„่ฃๅœจไธ€่ตท๏ผŒๅฐฑๅคงๅŠŸๅ‘Šๆˆไบ†๏ผ
iface = gr.Interface(fn=classify_image,
inputs=image,
outputs=label,
title="AI ๆ —ๅ–‰่œ‚่™Žใ€่—ๅญ”้›€ใ€ๆˆดๅ‹ใ€้ฑŸๅŠๆญไบžๆฐด็บ่พจ่ญ˜ๆฉŸ",
description=some_text,
examples=sample_images, live=True)
iface.launch()