-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathclf.py
executable file
·29 lines (23 loc) · 877 Bytes
/
clf.py
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
from torchvision import models, transforms
import torch
from PIL import Image
def predict(image_path):
resnet = models.resnet101(pretrained=True)
#https://pytorch.org/docs/stable/torchvision/models.html
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
)])
img = Image.open(image_path)
batch_t = torch.unsqueeze(transform(img), 0)
resnet.eval()
out = resnet(batch_t)
with open('imagenet_classes.txt') as f:
classes = [line.strip() for line in f.readlines()]
prob = torch.nn.functional.softmax(out, dim=1)[0] * 100
_, indices = torch.sort(out, descending=True)
return [(classes[idx], prob[idx].item()) for idx in indices[0][:5]]