File size: 1,348 Bytes
2b880c6
 
 
 
 
 
 
 
 
d77ad2a
 
2b880c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
"""image classification general.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1IKVz7857OWmXGom1Z2zq884jI84gkSUx
"""

#!pip install gradio
#!pip install transformers torch

import gradio as gr
from transformers import ViTImageProcessor, AutoModelForImageClassification
from PIL import Image
import torch

# Load pre-trained model and feature extractor
model_name = "google/vit-base-patch16-224"
feature_extractor = ViTImageProcessor.from_pretrained(model_name)
model = AutoModelForImageClassification.from_pretrained(model_name)

# Define the prediction function
def classify_image(img):
    inputs = feature_extractor(images=img, return_tensors="pt")
    with torch.no_grad():
        outputs = model(**inputs)
    logits = outputs.logits
    predicted_class_idx = logits.argmax(-1).item()
    predicted_label = model.config.id2label[predicted_class_idx]
    return predicted_label

# Build the Gradio interface
interface = gr.Interface(fn=classify_image,
                         inputs=gr.Image(type="pil"),
                         outputs="text",
                         title="Image Classification with ViT",
                         description="Upload an image and classify it using Vision Transformer (ViT)")

# Launch the app
interface.launch()