File size: 1,193 Bytes
bb814df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import time
from PIL import Image
from timm.data import resolve_data_config
import torch
from torchvision.transforms import transforms

model = torch.load('model.pth').to("cuda")
model.eval()
config = resolve_data_config({}, model=model)
transform = transforms.Compose([
                transforms.Resize((384, 384)),
                transforms.ToTensor(),
                transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
            ])

with open("tags.json", "r") as file:
    tags = json.load(file)
allowed_tags = sorted(tags)
allowed_tags.extend(["placeholder0", "placeholder1", "placeholder2"])
tag_count = len(allowed_tags)


image_path="path/to/your/image.png"
start = time.time()
img = Image.open(image_path).convert('RGB')
tensor = transform(img).unsqueeze(0).to("cuda") # transform and add batch dimension

with torch.no_grad():
    out = model(tensor)
probabilities = torch.nn.functional.sigmoid(out[0])

top10_prob, top10_catid = torch.topk(probabilities, 100)
for i in range(top10_prob.size(0)):
    print(allowed_tags[top10_catid[i]], top10_prob[i].item())
end = time.time()
print(f'Executed in {end - start} seconds')
print("\n\n", end="")