File size: 1,209 Bytes
878b93c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a142643
878b93c
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import math
import time
from PIL import Image
import torch
from torchvision.transforms import transforms

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = torch.load("path/to/your/model.pth")
model.to(device)
model.eval()

transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

with open("tags_8034.json", "r") as f:
    tags = json.load(f)
    tags.append("placeholder0")
    tags = sorted(tags)

image_path = "path/to/your/image.jpg"
start = time.time()
img = Image.open(image_path).convert('RGB')
aspect_ratio = img.width / img.height
new_height = math.sqrt(512 ** 2 / aspect_ratio)
new_width = aspect_ratio * new_height
img.thumbnail((int(new_width), int(new_height)), Image.LANCZOS)
tensor = transform(img).unsqueeze(0).to(device)
with torch.no_grad():
    out = model(tensor)
probabilities = torch.nn.functional.sigmoid(out[0])

indices = torch.where(probabilities > 0.3)[0]
values = probabilities[indices]

for i in range(indices.size(0)):
    print(tags[indices[i]], values[i].item())

end = time.time()
print(f'Executed in {end - start} seconds')
print("\n\n", end="")