Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -4,26 +4,29 @@ from PIL import Image
|
|
4 |
import gradio as gr
|
5 |
import os
|
6 |
|
7 |
-
#
|
8 |
device = torch.device('cpu')
|
9 |
|
10 |
-
#
|
11 |
model = models.resnet50(weights=None)
|
12 |
|
13 |
-
#
|
14 |
model.fc = torch.nn.Linear(2048, 37)
|
15 |
|
|
|
16 |
model.load_state_dict(torch.load('./resnet50_model_weights.pth', map_location=device))
|
17 |
|
|
|
18 |
model.eval()
|
19 |
|
|
|
20 |
transform = transforms.Compose([
|
21 |
transforms.Resize((224, 224)),
|
22 |
transforms.ToTensor(),
|
23 |
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
24 |
])
|
25 |
|
26 |
-
#
|
27 |
class_names = ['Abyssinian (阿比西尼亞貓)', 'American Bulldog (美國鬥牛犬)', 'American Pit Bull Terrier (美國比特鬥牛梗)',
|
28 |
'Basset Hound (巴吉度獵犬)', 'Beagle (米格魯)', 'Bengal (孟加拉貓)', 'Birman (緬甸貓)', 'Bombay (孟買貓)',
|
29 |
'Boxer (拳師犬)', 'British Shorthair (英國短毛貓)', 'Chihuahua (吉娃娃)', 'Egyptian Mau (埃及貓)',
|
@@ -35,47 +38,41 @@ class_names = ['Abyssinian (阿比西尼亞貓)', 'American Bulldog (美國鬥
|
|
35 |
'Siamese (暹羅貓)', 'Sphynx (無毛貓)', 'Staffordshire Bull Terrier (史塔福郡鬥牛犬)',
|
36 |
'Wheaten Terrier (小麥色梗)', 'Yorkshire Terrier (約克夏犬)']
|
37 |
|
38 |
-
#
|
39 |
def classify_image(image):
|
40 |
-
|
41 |
-
image = transform(image).unsqueeze(0).to(device)
|
42 |
with torch.no_grad():
|
43 |
-
# Make predictions using the model
|
44 |
outputs = model(image)
|
45 |
-
|
46 |
-
probabilities = torch.nn.functional.softmax(
|
47 |
-
# Get the top 3 predictions
|
48 |
-
probabilities, indices = torch.topk(probabilities, k=3)
|
49 |
-
# Return the class names with their corresponding probabilities
|
50 |
predictions = [(class_names[idx], prob.item()) for idx, prob in zip(indices[0], probabilities[0])]
|
51 |
-
return {class_name: prob for class_name, prob in predictions}
|
52 |
|
53 |
-
#
|
54 |
examples_path = './examples'
|
55 |
|
56 |
-
# Check if the example images folder exists
|
57 |
if os.path.exists(examples_path):
|
58 |
print(f"[INFO] Found examples folder at {examples_path}")
|
59 |
else:
|
60 |
print(f"[ERROR] Examples folder not found at {examples_path}")
|
61 |
|
62 |
-
#
|
63 |
examples = [[examples_path + "/" + img] for img in os.listdir(examples_path)]
|
64 |
|
65 |
-
#
|
66 |
-
|
67 |
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
|
|
4 |
import gradio as gr
|
5 |
import os
|
6 |
|
7 |
+
# 使用 CPU
|
8 |
device = torch.device('cpu')
|
9 |
|
10 |
+
# 定義 ResNet-50 模型架構(不使用預訓練權重)
|
11 |
model = models.resnet50(weights=None)
|
12 |
|
13 |
+
# 修改模型的全連接層,輸出 37 個類別
|
14 |
model.fc = torch.nn.Linear(2048, 37)
|
15 |
|
16 |
+
# 加載模型權重
|
17 |
model.load_state_dict(torch.load('./resnet50_model_weights.pth', map_location=device))
|
18 |
|
19 |
+
# 設置模型為評估模式
|
20 |
model.eval()
|
21 |
|
22 |
+
# 定義影像預處理
|
23 |
transform = transforms.Compose([
|
24 |
transforms.Resize((224, 224)),
|
25 |
transforms.ToTensor(),
|
26 |
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
27 |
])
|
28 |
|
29 |
+
# 定義類別名稱
|
30 |
class_names = ['Abyssinian (阿比西尼亞貓)', 'American Bulldog (美國鬥牛犬)', 'American Pit Bull Terrier (美國比特鬥牛梗)',
|
31 |
'Basset Hound (巴吉度獵犬)', 'Beagle (米格魯)', 'Bengal (孟加拉貓)', 'Birman (緬甸貓)', 'Bombay (孟買貓)',
|
32 |
'Boxer (拳師犬)', 'British Shorthair (英國短毛貓)', 'Chihuahua (吉娃娃)', 'Egyptian Mau (埃及貓)',
|
|
|
38 |
'Siamese (暹羅貓)', 'Sphynx (無毛貓)', 'Staffordshire Bull Terrier (史塔福郡鬥牛犬)',
|
39 |
'Wheaten Terrier (小麥色梗)', 'Yorkshire Terrier (約克夏犬)']
|
40 |
|
41 |
+
# 定義預測函數
|
42 |
def classify_image(image):
|
43 |
+
image = transform(image).unsqueeze(0).to(device) # 確保影像資料處理在 CPU 上
|
|
|
44 |
with torch.no_grad():
|
|
|
45 |
outputs = model(image)
|
46 |
+
probabilities, indices = torch.topk(outputs, k=3) # 取得前3個預測
|
47 |
+
probabilities = torch.nn.functional.softmax(probabilities, dim=1) # 將結果轉換為機率
|
|
|
|
|
|
|
48 |
predictions = [(class_names[idx], prob.item()) for idx, prob in zip(indices[0], probabilities[0])]
|
49 |
+
return {class_name: f"{prob * 100:.2f}%" for class_name, prob in predictions}
|
50 |
|
51 |
+
# 設置 examples 路徑
|
52 |
examples_path = './examples'
|
53 |
|
|
|
54 |
if os.path.exists(examples_path):
|
55 |
print(f"[INFO] Found examples folder at {examples_path}")
|
56 |
else:
|
57 |
print(f"[ERROR] Examples folder not found at {examples_path}")
|
58 |
|
59 |
+
# Gradio 介面
|
60 |
examples = [[examples_path + "/" + img] for img in os.listdir(examples_path)]
|
61 |
|
62 |
+
# 使用 Markdown 顯示 37 個品種
|
63 |
+
breed_list = "### Recognizable Breeds\n" + "\n".join([f"- {breed}" for breed in class_names])
|
64 |
|
65 |
+
demo = gr.Blocks()
|
66 |
+
|
67 |
+
with demo:
|
68 |
+
gr.Markdown("# Oxford Pet 🐕🐈 Recognizable Breeds")
|
69 |
+
gr.Markdown(breed_list) # 用 Markdown 顯示品種列表
|
70 |
+
gr.Interface(fn=classify_image,
|
71 |
+
inputs=gr.Image(type="pil"), # 只需要圖片輸入
|
72 |
+
outputs=[gr.Label(num_top_classes=3, label="Top 3 Predictions")],
|
73 |
+
examples=examples,
|
74 |
+
title='Oxford Pet 🐈🐕',
|
75 |
+
description='A ResNet50-based model for classifying 37 different pet breeds.',
|
76 |
+
article="[Oxford Project](https://github.com/Eric-Chung-0511/Learning-Record/tree/main/Data%20Science%20Projects/The%20Oxford-IIIT%20Pet%20Project)").launch()
|
77 |
+
|
78 |
+
demo.launch()
|