Spaces:
Runtime error
Runtime error
Create yolov5_classify.py
Browse files- yolov5_classify.py +45 -0
yolov5_classify.py
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from models.common import DetectMultiBackend
|
3 |
+
from torchvision import transforms
|
4 |
+
import gradio as gr
|
5 |
+
import requests
|
6 |
+
from PIL import Image
|
7 |
+
|
8 |
+
weights='/content/drive/MyDrive/yolov5/yolov5s-cls.pt'
|
9 |
+
|
10 |
+
model = DetectMultiBackend(weights)
|
11 |
+
|
12 |
+
# load imagenet 1000 labels
|
13 |
+
response = requests.get("https://git.io/JJkYN")
|
14 |
+
labels = response.text.split("\n")
|
15 |
+
|
16 |
+
def preprocess_image(inp):
|
17 |
+
# Define the preprocessing steps
|
18 |
+
preprocess = transforms.Compose([
|
19 |
+
transforms.Resize(256),
|
20 |
+
transforms.CenterCrop(224),
|
21 |
+
transforms.ToTensor(),
|
22 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
23 |
+
])
|
24 |
+
# Apply the preprocessing steps to the image
|
25 |
+
image = preprocess(inp)
|
26 |
+
# Convert the image to a PyTorch tensor
|
27 |
+
image = torch.tensor(image).unsqueeze(0)
|
28 |
+
|
29 |
+
return image
|
30 |
+
|
31 |
+
def predict(inp):
|
32 |
+
|
33 |
+
with torch.no_grad():
|
34 |
+
prediction = torch.nn.functional.softmax(model(preprocess_image(inp))[0], dim=0)
|
35 |
+
|
36 |
+
print(prediction)
|
37 |
+
confidences = {labels[i]: float(prediction[i]) for i in range(1000)}
|
38 |
+
return confidences
|
39 |
+
|
40 |
+
|
41 |
+
gr.Interface(fn=predict,
|
42 |
+
inputs=gr.Image(type="pil"),
|
43 |
+
outputs="label",labels=labels).launch(debug=True)
|
44 |
+
|
45 |
+
#outputs=gr.Label(num_top_classes=5))
|