File size: 1,789 Bytes
b60902e d82d587 b60902e f94173d d82d587 b60902e f94173d b60902e ac1d126 b60902e ac1d126 b60902e c446819 55c6bb4 c446819 b60902e 55c6bb4 d82d587 55c6bb4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | import torch
import torchvision.transforms as transforms
from torchvision import models
from PIL import Image
import gradio as gr
# ๋ชจ๋ธ ํด๋์ค ์ ์ (ResNet18)
class MyModel(torch.nn.Module):
def __init__(self, num_classes):
super(MyModel, self).__init__()
self.model = models.resnet18(weights=None) # ResNet18 ๋ชจ๋ธ ์ฌ์ฉ
self.model.fc = torch.nn.Linear(self.model.fc.in_features, num_classes) # ๋ง์ง๋ง ๋ ์ด์ด ์์
def forward(self, x):
return self.model(x)
# ๋ชจ๋ธ ์ด๊ธฐํ
num_classes = 6 # ํด๋์ค ์์ ๋ง๊ฒ ์ค์
model = MyModel(num_classes)
# ๋ชจ๋ธ ๊ฐ์ค์น ๋ก๋ (CPU๋ก ๋งคํ)
model.load_state_dict(torch.load('resnet18_finetuned_2.pth', map_location=torch.device('cpu')), strict=False)
model.eval()
# ๋ฐ์ดํฐ ๋ณํ ์ ์
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
# ํด๋์ค ์ด๋ฆ ๋ฆฌ์คํธ ์ ์
class_names = ['disposablecup', 'envmark', 'label', 'mug', 'nonlabel', 'reusablecup']
def predict(image):
image = transform(image).unsqueeze(0)
with torch.no_grad():
outputs = model(image)
print("Raw outputs:", outputs) # ์๋ณธ ์ถ๋ ฅ๊ฐ ํ์ธ
_, predicted = torch.max(outputs, 1)
label = class_names[predicted.item()]
if label in ['disposablecup','label'] : result = "Failed"
else : result = "Successed (+1)"
# ์์ธก ๊ฒฐ๊ณผ์ ์๋ณธ ์ถ๋ ฅ๊ฐ์ ๋ชจ๋ ๋ฐํ
return result # ์๋ณธ ์ถ๋ ฅ๊ฐ์ NumPy ๋ฐฐ์ด๋ก ๋ณํํ์ฌ ๋ฐํ
# Gradio ์ธํฐํ์ด์ค ์ค์ (๋ ๊ฐ์ ์ถ๋ ฅ)
iface = gr.Interface(fn=predict, inputs=gr.Image(type='pil'), outputs=['label', 'numpy'], live=True)
iface.launch()
|