BhumikaMak commited on
Commit
71b8b5d
·
1 Parent(s): 862de68

Add: support for yolov8

Browse files
Files changed (2) hide show
  1. app.py +4 -1
  2. yolov8.py +78 -0
app.py CHANGED
@@ -4,6 +4,7 @@ from PIL import Image
4
  import torchvision.transforms as transforms
5
  import gradio as gr
6
  from yolov5 import xai_yolov5
 
7
 
8
  def process_image(image, yolo_versions=["yolov5"]):
9
  image = np.array(image)
@@ -13,6 +14,8 @@ def process_image(image, yolo_versions=["yolov5"]):
13
  for yolo_version in yolo_versions:
14
  if yolo_version == "yolov5":
15
  result_images.append(xai_yolov5(image))
 
 
16
  else:
17
  result_images.append((Image.fromarray(image), f"{yolo_version} not yet implemented."))
18
  return result_images
@@ -23,7 +26,7 @@ interface = gr.Interface(
23
  inputs=[
24
  gr.Image(type="pil", label="Upload an Image"),
25
  gr.CheckboxGroup(
26
- choices=["yolov3", "yolov5", "yolov7", "yolov8", "yolov10"],
27
  value=["yolov5"], # Set default selection to YOLOv5
28
  label="Select Model(s)",
29
  )
 
4
  import torchvision.transforms as transforms
5
  import gradio as gr
6
  from yolov5 import xai_yolov5
7
+ from yolov8 import xai_yolov8
8
 
9
  def process_image(image, yolo_versions=["yolov5"]):
10
  image = np.array(image)
 
14
  for yolo_version in yolo_versions:
15
  if yolo_version == "yolov5":
16
  result_images.append(xai_yolov5(image))
17
+ elif yolo_version == "yolov8":
18
+ result_images.append(xai_yolov8(image))
19
  else:
20
  result_images.append((Image.fromarray(image), f"{yolo_version} not yet implemented."))
21
  return result_images
 
26
  inputs=[
27
  gr.Image(type="pil", label="Upload an Image"),
28
  gr.CheckboxGroup(
29
+ choices=["yolov5", "yolov8", "yolov10"],
30
  value=["yolov5"], # Set default selection to YOLOv5
31
  label="Select Model(s)",
32
  )
yolov8.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import cv2
3
+ import numpy as np
4
+ from PIL import Image
5
+ import torchvision.transforms as transforms
6
+ from pytorch_grad_cam import EigenCAM
7
+ from pytorch_grad_cam.utils.image import show_cam_on_image, scale_cam_image
8
+ from ultralytics import YOLO
9
+
10
+ COLORS = np.random.uniform(0, 255, size=(80, 3))
11
+ def parse_detections_yolov8(results):
12
+ boxes, colors, names = [], [], []
13
+ detections = results.boxes
14
+ for box in detections:
15
+ confidence = box.conf[0].item()
16
+ if confidence < 0.2:
17
+ continue
18
+ xmin, ymin, xmax, ymax = map(int, box.xyxy[0].tolist())
19
+ category = int(box.cls[0].item())
20
+ name = results.names[category]
21
+ boxes.append((xmin, ymin, xmax, ymax))
22
+ colors.append(COLORS[category])
23
+ names.append(name)
24
+ return boxes, colors, names
25
+
26
+
27
+ def draw_detections(boxes, colors, names, img):
28
+ for box, color, name in zip(boxes, colors, names):
29
+ xmin, ymin, xmax, ymax = box
30
+ cv2.rectangle(img, (xmin, ymin), (xmax, ymax), color, 2)
31
+ cv2.putText(img, name, (xmin, ymin - 5),
32
+ cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2,
33
+ lineType=cv2.LINE_AA)
34
+ return img
35
+
36
+
37
+ def generate_cam_image(model, target_layers, tensor, rgb_img, boxes):
38
+ cam = EigenCAM(model, target_layers)
39
+ grayscale_cam = cam(tensor)[0, :, :]
40
+ img_float = np.float32(rgb_img) / 255
41
+
42
+ # Generate Grad-CAM
43
+ cam_image = show_cam_on_image(img_float, grayscale_cam, use_rgb=True)
44
+
45
+ # Renormalize Grad-CAM inside bounding boxes
46
+ renormalized_cam = np.zeros(grayscale_cam.shape, dtype=np.float32)
47
+ for x1, y1, x2, y2 in boxes:
48
+ renormalized_cam[y1:y2, x1:x2] = scale_cam_image(grayscale_cam[y1:y2, x1:x2].copy())
49
+ renormalized_cam = scale_cam_image(renormalized_cam)
50
+ renormalized_cam_image = show_cam_on_image(img_float, renormalized_cam, use_rgb=True)
51
+
52
+ return cam_image, renormalized_cam_image
53
+
54
+
55
+ def xai_yolov8(image):
56
+ # Load YOLOv8 model
57
+ model = YOLO('yolov8n.pt') # Load YOLOv8 nano model
58
+ model.to('cpu')
59
+ model.eval()
60
+
61
+ # Run YOLO detection
62
+ results = model(image)
63
+ boxes, colors, names = parse_detections_yolov8(results[0])
64
+ detections_img = draw_detections(boxes, colors, names, image.copy())
65
+
66
+ # Prepare input tensor for Grad-CAM
67
+ img_float = np.float32(image) / 255
68
+ transform = transforms.ToTensor()
69
+ tensor = transform(img_float).unsqueeze(0)
70
+
71
+ # Grad-CAM visualization
72
+ target_layers = [model.model.model[-2]] # Adjust the target layer if required
73
+ cam_image, renormalized_cam_image = generate_cam_image(model.model, target_layers, tensor, image, boxes)
74
+
75
+ # Combine results
76
+ final_image = np.hstack((image, cam_image, renormalized_cam_image))
77
+ caption = "Results using YOLOv8"
78
+ return Image.fromarray(final_image), caption