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
| import torch from torchvision import models, transforms from PIL import Image
model = models.resnet50(pretrained=True)
model.eval()
preprocess = 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_path = "./dog.jpg"
img = Image.open(img_path)
img_t = preprocess(img)
batch_t = torch.unsqueeze(img_t, 0)
with torch.no_grad(): out = model(batch_t)
with open("imagenet_classes.txt") as f: labels = [line.strip() for line in f.readlines()]
_, index = torch.max(out, 1)
percentage = torch.nn.functional.softmax(out, dim=1)[0] * 100
print(labels[index[0]], percentage[index[0]].item())
|