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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import torch
|
| 3 |
+
import cv2
|
| 4 |
+
import warnings
|
| 5 |
+
warnings.filterwarnings('ignore')
|
| 6 |
+
import numpy as np
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import torchvision.transforms as transforms
|
| 9 |
+
from pytorch_grad_cam import EigenCAM
|
| 10 |
+
from pytorch_grad_cam.utils.image import show_cam_on_image, scale_cam_image
|
| 11 |
+
import gradio as gr
|
| 12 |
+
import yaml
|
| 13 |
+
import requests
|
| 14 |
+
from pytorch_grad_cam import DeepFeatureFactorization
|
| 15 |
+
from pytorch_grad_cam.utils.image import show_cam_on_image, preprocess_image
|
| 16 |
+
from pytorch_grad_cam.utils.image import deprocess_image, show_factorization_on_image
|
| 17 |
+
COLORS = np.random.uniform(0, 255, size=(80, 3))
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def parse_detections(results):
|
| 21 |
+
detections = results.pandas().xyxy[0].to_dict()
|
| 22 |
+
boxes, colors, names, classes = [], [], [], []
|
| 23 |
+
for i in range(len(detections["xmin"])):
|
| 24 |
+
confidence = detections["confidence"][i]
|
| 25 |
+
if confidence < 0.2:
|
| 26 |
+
continue
|
| 27 |
+
xmin, ymin = int(detections["xmin"][i]), int(detections["ymin"][i])
|
| 28 |
+
xmax, ymax = int(detections["xmax"][i]), int(detections["ymax"][i])
|
| 29 |
+
name, category = detections["name"][i], int(detections["class"][i])
|
| 30 |
+
boxes.append((xmin, ymin, xmax, ymax))
|
| 31 |
+
colors.append(COLORS[category])
|
| 32 |
+
names.append(name)
|
| 33 |
+
classes.append(category)
|
| 34 |
+
return boxes, colors, names, classes
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def draw_detections(boxes, colors, names, classes, img):
|
| 38 |
+
for box, color, name, cls in zip(boxes, colors, names, classes):
|
| 39 |
+
xmin, ymin, xmax, ymax = box
|
| 40 |
+
label = f"{cls}: {name}" # Combine class ID and name
|
| 41 |
+
cv2.rectangle(img, (xmin, ymin), (xmax, ymax), color, 2)
|
| 42 |
+
cv2.putText(
|
| 43 |
+
img, label, (xmin, ymin - 5),
|
| 44 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2,
|
| 45 |
+
lineType=cv2.LINE_AA
|
| 46 |
+
)
|
| 47 |
+
return img
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def generate_cam_image(model, target_layers, tensor, rgb_img, boxes):
|
| 51 |
+
cam = EigenCAM(model, target_layers)
|
| 52 |
+
grayscale_cam = cam(tensor)[0, :, :]
|
| 53 |
+
img_float = np.float32(rgb_img) / 255
|
| 54 |
+
cam_image = show_cam_on_image(img_float, grayscale_cam, use_rgb=True)
|
| 55 |
+
renormalized_cam = np.zeros(grayscale_cam.shape, dtype=np.float32)
|
| 56 |
+
for x1, y1, x2, y2 in boxes:
|
| 57 |
+
renormalized_cam[y1:y2, x1:x2] = scale_cam_image(grayscale_cam[y1:y2, x1:x2].copy())
|
| 58 |
+
renormalized_cam = scale_cam_image(renormalized_cam)
|
| 59 |
+
renormalized_cam_image = show_cam_on_image(img_float, renormalized_cam, use_rgb=True)
|
| 60 |
+
|
| 61 |
+
return cam_image, renormalized_cam_image
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def xai_yolov5(image):
|
| 65 |
+
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
|
| 66 |
+
model.eval()
|
| 67 |
+
model.cpu()
|
| 68 |
+
|
| 69 |
+
target_layers = [model.model.model.model[-2]] # Grad-CAM target layer
|
| 70 |
+
|
| 71 |
+
# Run YOLO detection
|
| 72 |
+
results = model([image])
|
| 73 |
+
boxes, colors, names, classes = parse_detections(results)
|
| 74 |
+
detections_img = draw_detections(boxes, colors, names,classes, image.copy())
|
| 75 |
+
|
| 76 |
+
# Prepare input tensor for Grad-CAM
|
| 77 |
+
img_float = np.float32(image) / 255
|
| 78 |
+
transform = transforms.ToTensor()
|
| 79 |
+
tensor = transform(img_float).unsqueeze(0)
|
| 80 |
+
|
| 81 |
+
# Grad-CAM visualization
|
| 82 |
+
cam_image, renormalized_cam_image = generate_cam_image(model, target_layers, tensor, image, boxes)
|
| 83 |
+
|
| 84 |
+
# Combine results
|
| 85 |
+
final_image = np.hstack((image, detections_img, renormalized_cam_image))
|
| 86 |
+
caption = "Results using YOLOv5"
|
| 87 |
+
return Image.fromarray(final_image), caption
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
# Check if CUDA is available
|
| 91 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 92 |
+
mean = [0.485, 0.456, 0.406] # Mean for RGB channels
|
| 93 |
+
std = [0.229, 0.224, 0.225] # Standard deviation for RGB channels
|
| 94 |
+
# Load YOLOv5 model and move it to the appropriate device
|
| 95 |
+
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True).to(device)
|
| 96 |
+
print(f"Loaded YOLOv5 model on {device}")
|
| 97 |
+
def create_labels(concept_scores, top_k=2):
|
| 98 |
+
"""Create a list with the category names of the top scoring categories."""
|
| 99 |
+
yolov5_categories_url = \
|
| 100 |
+
"https://github.com/ultralytics/yolov5/raw/master/data/coco128.yaml" # URL to the YOLOv5 categories file
|
| 101 |
+
yaml_data = requests.get(yolov5_categories_url).text
|
| 102 |
+
labels = yaml.safe_load(yaml_data)['names'] # Parse the YAML file to get class names
|
| 103 |
+
|
| 104 |
+
concept_categories = np.argsort(concept_scores, axis=1)[:, ::-1][:, :top_k]
|
| 105 |
+
concept_labels_topk = []
|
| 106 |
+
for concept_index in range(concept_categories.shape[0]):
|
| 107 |
+
categories = concept_categories[concept_index, :]
|
| 108 |
+
concept_labels = []
|
| 109 |
+
for category in categories:
|
| 110 |
+
score = concept_scores[concept_index, category]
|
| 111 |
+
label = f"{labels[category]}:{score:.2f}"
|
| 112 |
+
concept_labels.append(label)
|
| 113 |
+
concept_labels_topk.append("\n".join(concept_labels))
|
| 114 |
+
return concept_labels_topk
|
| 115 |
+
|
| 116 |
+
def get_image_from_url(url, device):
|
| 117 |
+
"""A function that gets a URL of an image,
|
| 118 |
+
and returns a numpy image and a preprocessed
|
| 119 |
+
torch tensor ready to pass to the model"""
|
| 120 |
+
|
| 121 |
+
img = np.array(Image.open("/home/drovco/Bhumika/NeuralVista/data/xai/sample1.jpeg"))
|
| 122 |
+
img = cv2.resize(img, (640, 640))
|
| 123 |
+
rgb_img_float = np.float32(img) /255.0
|
| 124 |
+
input_tensor = torch.from_numpy(rgb_img_float).permute(2, 0, 1).unsqueeze(0).to(device)
|
| 125 |
+
return img, rgb_img_float, input_tensor
|
| 126 |
+
|
| 127 |
+
def visualize_image(model, img_url, n_components=20, top_k=1, lyr_idx = 2):
|
| 128 |
+
img, rgb_img_float, input_tensor = get_image_from_url(img_url, device)
|
| 129 |
+
|
| 130 |
+
# Specify the target layer for DeepFeatureFactorization (e.g., YOLO's backbone)
|
| 131 |
+
target_layer = model.model.model.model[-lyr_idx] # Select a feature extraction layer
|
| 132 |
+
|
| 133 |
+
dff = DeepFeatureFactorization(model=model.model, target_layer=target_layer)
|
| 134 |
+
|
| 135 |
+
# Run DFF on the input tensor
|
| 136 |
+
concepts, batch_explanations = dff(input_tensor, n_components)
|
| 137 |
+
|
| 138 |
+
# Softmax normalization
|
| 139 |
+
concept_outputs = torch.softmax(torch.from_numpy(concepts), axis=-1).numpy()
|
| 140 |
+
concept_label_strings = create_labels(concept_outputs, top_k=top_k)
|
| 141 |
+
|
| 142 |
+
# Visualize explanations
|
| 143 |
+
visualization = show_factorization_on_image(rgb_img_float,
|
| 144 |
+
batch_explanations[0],
|
| 145 |
+
image_weight=0.2,
|
| 146 |
+
concept_labels=concept_label_strings)
|
| 147 |
+
|
| 148 |
+
import matplotlib.pyplot as plt
|
| 149 |
+
plt.imshow(visualization)
|
| 150 |
+
plt.savefig("test" + str(lyr_idx) + ".png")
|
| 151 |
+
result = np.hstack((img, visualization))
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
# Resize for visualization
|
| 155 |
+
if result.shape[0] > 500:
|
| 156 |
+
result = cv2.resize(result, (result.shape[1]//4, result.shape[0]//4))
|
| 157 |
+
|
| 158 |
+
return result
|
| 159 |
+
|
| 160 |
+
# Test with images
|
| 161 |
+
for indx in range(2,12):
|
| 162 |
+
Image.fromarray(visualize_image(model,
|
| 163 |
+
"https://github.com/jacobgil/pytorch-grad-cam/blob/master/examples/both.png?raw=true", lyr_idx = indx))
|