Image-Tagging
Sample inference script for torchscript exported image-tagger.
The following script should be run from the model export directory:
sample_tagger.py
1
import torch
2
import numpy as np
3
from PIL import Image
4
import json
5
6
with open('class_mapping.json') as data:
7
mappings = json.load(data)
8
9
class_mapping = {item['model_idx']: item['tag_string'] for item in mappings}
10
11
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
12
13
model = torch.jit.load('model.pt').to(device)
14
15
image_path = '/path/to/your/image'
16
image = Image.open(image_path)
17
# Transform your image according to the transforms.json as in
18
# https://help.hasty.ai/model-playground/image-transformations
19
image = np.array(image)
20
# Convert to torch tensor
21
x = torch.from_numpy(image).to(device)
22
with torch.no_grad():
23
# Convert to channels first, add batch dimension, convert to float datatype
24
x = x.permute(2, 0, 1).unsqueeze(dim=0).float()
25
y = model(x)
26
y = torch.sigmoid(y).squeeze()
27
# All classes with probabilities > 0.5 are considered present in
28
# the input. You can tweak this 0.5 threshold if you desire.
29
idxs = torch.where(y > 0.5)[0].cpu().numpy()
30
present_tags = []
31
for idx in idxs:
32
present_tags.append(
33
class_mapping[idx]
34
)
35
print("Tags for input:", present_tags)
Copied!
Last modified 5mo ago
Copy link