006f86 commited on
Commit
c991e43
·
1 Parent(s): dff62de

Added yolov8, updated app.py

Browse files
Files changed (2) hide show
  1. app.py +86 -15
  2. yolov8x.pt +3 -0
app.py CHANGED
@@ -4,9 +4,15 @@ import torch.nn as nn
4
  from torchvision import transforms
5
  from torchvision.models import efficientnet_v2_s, EfficientNet_V2_S_Weights
6
  from PIL import Image
 
 
 
7
  import json
8
  import os
9
 
 
 
 
10
  MODEL_PATH = "best_model.pth"
11
  with open("class_names.json", "r") as f:
12
  CLASS_NAMES = json.load(f)
@@ -28,29 +34,94 @@ transform = transforms.Compose([
28
  transforms.Normalize(mean=mean, std=std),
29
  ])
30
 
31
- def predict(image):
32
- image = transform(image).unsqueeze(0).to(device)
33
- with torch.no_grad():
34
- outputs = model(image)
35
- probs = torch.nn.functional.softmax(outputs, dim=1)[0]
36
 
37
- results = {CLASS_NAMES[i]: float(probs[i]) for i in range(len(CLASS_NAMES))}
 
 
 
 
 
38
 
39
- sorted_indices = torch.argsort(probs, descending=True)
40
- top5_indices = sorted_indices[:5]
 
 
 
41
 
42
- top5_results = {CLASS_NAMES[i]: float(probs[i]) for i in top5_indices}
 
 
 
 
 
 
43
 
44
- return top5_results, results
 
 
 
 
 
45
 
 
 
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  demo = gr.Interface(
48
- fn=predict,
49
- inputs=gr.Image(type="pil"),
50
- outputs=[gr.Label(label="Prediction"), gr.JSON(label="Confidence Scores")],
 
 
 
51
  title="StrAI - Cat Identifier",
52
- description="Upload an image to identify which cat it is."
53
  )
54
 
55
  if __name__ == "__main__":
56
- demo.launch()
 
4
  from torchvision import transforms
5
  from torchvision.models import efficientnet_v2_s, EfficientNet_V2_S_Weights
6
  from PIL import Image
7
+ import numpy as np
8
+ import cv2
9
+ from ultralytics import YOLO
10
  import json
11
  import os
12
 
13
+ # ---------------------------
14
+ # 1. Load EfficientNet model
15
+ # ---------------------------
16
  MODEL_PATH = "best_model.pth"
17
  with open("class_names.json", "r") as f:
18
  CLASS_NAMES = json.load(f)
 
34
  transforms.Normalize(mean=mean, std=std),
35
  ])
36
 
37
+ # ---------------------------
38
+ # 2. Load YOLOv8 model
39
+ # ---------------------------
40
+ yolo_model = YOLO("yolov8x.pt")
 
41
 
42
+ # ---------------------------
43
+ # 3. Detection + Identification Pipeline
44
+ # ---------------------------
45
+ def detect_and_identify(image: Image.Image):
46
+ # Convert PIL to OpenCV (numpy)
47
+ image_cv = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
48
 
49
+ # Run YOLOv8 detection
50
+ results = yolo_model(image_cv)
51
+ boxes = results[0].boxes
52
+ names = results[0].names
53
+ detections = boxes.data.cpu().numpy()
54
 
55
+ # Filter for cats only
56
+ valid_detections = []
57
+ for det in detections:
58
+ x1, y1, x2, y2, conf, cls = det
59
+ class_name = names[int(cls)]
60
+ if class_name == "cat":
61
+ valid_detections.append(det)
62
 
63
+ if not valid_detections:
64
+ return (
65
+ None,
66
+ {"Error": "No cat detected in the image."},
67
+ {"Info": "Please upload an image containing one or more visible cats."}
68
+ )
69
 
70
+ cropped_images = []
71
+ predictions = {}
72
 
73
+ for i, det in enumerate(valid_detections):
74
+ x1, y1, x2, y2, conf, cls = det
75
+ x1, y1, x2, y2 = map(int, [x1, y1, x2, y2])
76
+
77
+ # Crop the detected cat
78
+ cropped_cat = image_cv[y1:y2, x1:x2]
79
+ cropped_pil = Image.fromarray(cv2.cvtColor(cropped_cat, cv2.COLOR_BGR2RGB))
80
+
81
+ # Preprocess for classifier
82
+ input_tensor = transform(cropped_pil).unsqueeze(0).to(device)
83
+
84
+ # Identify using EfficientNet
85
+ with torch.no_grad():
86
+ outputs = model(input_tensor)
87
+ probs = torch.nn.functional.softmax(outputs, dim=1)[0]
88
+
89
+ # Get top prediction
90
+ top_idx = torch.argmax(probs).item()
91
+ top_label = CLASS_NAMES[top_idx]
92
+ confidence = float(probs[top_idx])
93
+
94
+ # Get Top 5 predictions only
95
+ top5_indices = torch.argsort(probs, descending=True)[:5]
96
+ top5_results = {CLASS_NAMES[j]: float(probs[j]) for j in top5_indices}
97
+
98
+ # Append image with caption (for Gallery)
99
+ cropped_images.append((cropped_pil, f"{top_label} ({confidence*100:.1f}%)"))
100
+
101
+ # Add JSON data for this cat
102
+ predictions[f"Cat {i+1} - {top_label}"] = {
103
+ "Top Prediction": top_label,
104
+ "Confidence": confidence,
105
+ "Top 5 Scores": top5_results
106
+ }
107
+
108
+
109
+ return cropped_images, predictions
110
+
111
+
112
+ # ---------------------------
113
+ # 4. Gradio Interface
114
+ # ---------------------------
115
  demo = gr.Interface(
116
+ fn=detect_and_identify,
117
+ inputs=gr.Image(type="pil", label="Upload Image"),
118
+ outputs=[
119
+ gr.Gallery(label="Detected Cats (Cropped)", columns=2, rows=2),
120
+ gr.JSON(label="Predictions per Cat")
121
+ ],
122
  title="StrAI - Cat Identifier",
123
+ description="Upload an image with one or more cats."
124
  )
125
 
126
  if __name__ == "__main__":
127
+ demo.launch()
yolov8x.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3df4ada6b4dad6d657868f2fdf7faecfb34dcfccf3a25c4b82079064718524c8
3
+ size 136890692