Team Ai
Apppublic

Hbvsa/Image_classification

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py73 linesDownload Raw Back to root
1import sys
2from os.path import abspath, dirname
3sys.path.append(abspath(dirname(__name__)))
4import gradio as gr
5import torch
6from os.path import dirname
7from torchvision import transforms
8from PIL import Image
9import yaml
10from torch import nn
11def image_classification():
12
13    with open(f"{dirname(abspath(__file__))}/config.yaml", 'r') as f:
14        config = yaml.load(f, Loader=yaml.FullLoader)
15        labels = config["labels"]
16
17    class DinoVisionTransformerClassifier(nn.Module):
18        def __init__(self):
19            super(DinoVisionTransformerClassifier, self).__init__()
20            self.transformer = torch.hub.load("facebookresearch/dinov2", "dinov2_vits14")
21            self.classifier = nn.Sequential(nn.Linear(384, 256), nn.ReLU(), nn.Linear(256, 2))
22
23        def forward(self, x):
24            x = self.transformer(x)
25            x = self.transformer.norm(x)
26            x = self.classifier(x)
27            return x
28
29    dino = DinoVisionTransformerClassifier()
30    model_path = f"{dirname(abspath(__file__))}/model.pth"
31    state_dict = torch.load(model_path)
32    dino.load_state_dict(state_dict)
33
34    def preprocess(img_path):
35        data_transforms = {
36            "test": transforms.Compose(
37                [
38                    transforms.Resize((224, 224)),
39                    transforms.ToTensor(),
40                    transforms.Normalize([0.4914, 0.4822, 0.4465], [0.2023, 0.1994, 0.2010]),
41                ]
42            )
43        }
44
45        img = Image.open(img_path).convert('RGB')
46        img_transformed = data_transforms['test'](img)
47
48        return img_transformed
49
50    def predict(img_path):
51        img = preprocess(img_path)
52        img = img.unsqueeze(0)
53        device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
54        dino.to(device)
55        dino.eval()
56        with torch.no_grad():
57            output = dino(img.to(device))
58
59        _, predicted = torch.max(output.data, 1)
60        print("Predicted", predicted[0])
61        return labels[predicted[0].item()]
62
63    demo = gr.Interface(
64        fn=predict,
65        inputs=gr.Image(type="filepath", label="Classify Image"),
66        outputs=gr.Textbox(label="Label"),
67        title="Person classifier",
68    )
69
70    demo.launch(share=True, debug=True)
71
72if __name__ == "__main__":
73    image_classification()