Spaces:
Sleeping
Sleeping
add app and requirements
Browse files- app.py +195 -0
- gradio_utils.py +175 -0
- models.py +81 -0
- requirements.txt +10 -0
app.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import cv2
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import timm
|
| 5 |
+
from ultralytics import YOLO
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
from PIL import Image as PILImage
|
| 9 |
+
from timm.utils.attention_extract import AttentionExtract
|
| 10 |
+
from glob import glob
|
| 11 |
+
import os
|
| 12 |
+
import argparse
|
| 13 |
+
from gradio_utils import classes, cropSquareCV, nms, classifier_transforms, get_sns_heatmap
|
| 14 |
+
from gradio_utils import make_thumbnail_gallery, annotate_bbox_on_image
|
| 15 |
+
from models import MCAClassifier
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 19 |
+
dirname = os.path.dirname(__file__)
|
| 20 |
+
|
| 21 |
+
detector = YOLO(os.path.join(dirname, 'models/MDV6-yolov10-e-1280.pt'))
|
| 22 |
+
|
| 23 |
+
classifier = timm.create_model("vit_large_patch14_dinov2.lvd142m", pretrained=False, num_classes=46, dynamic_img_size=True)
|
| 24 |
+
classifier.load_state_dict(torch.load(os.path.join(dirname, 'models/crop_classifier_half.pt'), map_location=device, weights_only=True))
|
| 25 |
+
classifier.to(device)
|
| 26 |
+
|
| 27 |
+
seq_model = MCAClassifier(depth=4)
|
| 28 |
+
seq_model.load_state_dict(torch.load(os.path.join(dirname, 'models/mca_classifier.pt'), map_location=device, weights_only=True))
|
| 29 |
+
seq_model.to(device)
|
| 30 |
+
extractor = AttentionExtract(seq_model, method='fx') # for the attention matrix
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def show_preds_image(image1, image2=None):
|
| 34 |
+
image_paths = [image1, image2]
|
| 35 |
+
predictions = []
|
| 36 |
+
embeddings_seq = []
|
| 37 |
+
|
| 38 |
+
gallery_images = []
|
| 39 |
+
table_data = []
|
| 40 |
+
img_list = []
|
| 41 |
+
crop_size = (200, 200)
|
| 42 |
+
|
| 43 |
+
# detection and independent classifier + save embeddings for mca classsifer
|
| 44 |
+
for image_path in image_paths:
|
| 45 |
+
if image_path is None:
|
| 46 |
+
continue
|
| 47 |
+
image = cv2.imread(image_path)
|
| 48 |
+
outputs = detector.predict(source=image_path, imgsz=1280, verbose=True, conf=0.25, device=device)
|
| 49 |
+
detections = nms(outputs[0].cpu().numpy().boxes, 0.5)
|
| 50 |
+
|
| 51 |
+
for i, (box_cls, conf, box) in enumerate(zip(detections.cls, detections.conf, detections.xyxy)):
|
| 52 |
+
if conf < 0.25:
|
| 53 |
+
continue
|
| 54 |
+
|
| 55 |
+
x1, y1, x2, y2 = map(int, box)
|
| 56 |
+
croppedimagecv = cropSquareCV(image, box.copy())[:, :, (2, 1, 0)]
|
| 57 |
+
croppedimage = Image.fromarray(croppedimagecv) # for classifier
|
| 58 |
+
im = cv2.resize(croppedimagecv, crop_size, interpolation=cv2.INTER_CUBIC) # for visualization
|
| 59 |
+
gallery_images.append(PILImage.fromarray(im)) # for gallery
|
| 60 |
+
img_list.append(im) # for attention matrix
|
| 61 |
+
if box_cls == 0:
|
| 62 |
+
x = classifier_transforms(croppedimage).unsqueeze(dim=0).to(device)
|
| 63 |
+
with torch.no_grad():
|
| 64 |
+
embeddings = classifier.forward_features(x)
|
| 65 |
+
embeddings_seq.append(embeddings[:, 0:1, :])
|
| 66 |
+
pred = classifier.forward_head(embeddings).softmax(dim=1).cpu()
|
| 67 |
+
|
| 68 |
+
scores = {classes[j]: float(pred[0][j]) for j in range(len(classes))}
|
| 69 |
+
top_class = max(scores, key=scores.get)
|
| 70 |
+
label_text = f"{top_class}: {scores[top_class]*100:.0f}%"
|
| 71 |
+
else:
|
| 72 |
+
if box_cls == 1:
|
| 73 |
+
label_text = "human"
|
| 74 |
+
elif box_cls == 2:
|
| 75 |
+
label_text = "vehicle"
|
| 76 |
+
|
| 77 |
+
predictions.append([(x1, y1, x2, y2), label_text, image_path])
|
| 78 |
+
|
| 79 |
+
# sequence-aware classifier
|
| 80 |
+
if len(embeddings_seq) > 0:
|
| 81 |
+
x = torch.concat(embeddings_seq, 1)
|
| 82 |
+
with torch.no_grad():
|
| 83 |
+
embeddings = seq_model.forward_blocks(x)
|
| 84 |
+
pred = classifier.forward_head(embeddings.swapaxes(0, 1)).cpu().softmax(dim=1)
|
| 85 |
+
oo = extractor(x)
|
| 86 |
+
am = oo[f'blocks.{len(oo)-1}.attn.softmax'].cpu().numpy()[0]
|
| 87 |
+
print(am.shape)
|
| 88 |
+
else:
|
| 89 |
+
pred = []
|
| 90 |
+
am = None
|
| 91 |
+
|
| 92 |
+
n = 0
|
| 93 |
+
for i, ((x1, y1, x2, y2), orig_label, image_path) in enumerate(predictions):
|
| 94 |
+
if orig_label in ["human", "vehicle"]:
|
| 95 |
+
table_data.append([i, orig_label, orig_label, image_path])
|
| 96 |
+
else:
|
| 97 |
+
top_class = max({classes[j]: float(pred[n][j]) for j in range(len(classes))}, key=lambda k: pred[n][classes.index(k)])
|
| 98 |
+
top_score = float(pred[n][classes.index(top_class)])*100
|
| 99 |
+
seq_label = f"{top_class}: {top_score:.0f}%"
|
| 100 |
+
table_data.append([i, orig_label, seq_label, image_path])
|
| 101 |
+
n += 1
|
| 102 |
+
|
| 103 |
+
# permutate bbox order to make the attention matrix easier to read
|
| 104 |
+
sp = [table_data[i][2].split(":")[0] for i in range(len(table_data))]
|
| 105 |
+
perm = sorted(range(len(sp)), key=lambda k: sp[k])
|
| 106 |
+
gallery_images = [gallery_images[i] for i in perm]
|
| 107 |
+
img_list = [img_list[i] for i in perm]
|
| 108 |
+
table_data = [table_data[i] for i in perm]
|
| 109 |
+
if am is not None:
|
| 110 |
+
not_animal = [x in ["human", "vehicle"] for x in [sp[i] for i in perm]]
|
| 111 |
+
not_animal_idx = [perm[i] for i in range(len(perm)) if not_animal[i]]
|
| 112 |
+
am_perm = []
|
| 113 |
+
for i in range(len(perm)):
|
| 114 |
+
if not_animal[i]:
|
| 115 |
+
continue
|
| 116 |
+
else:
|
| 117 |
+
am_perm.append(perm[i] - sum([perm[i] > k for k in not_animal_idx]))
|
| 118 |
+
am = am[:, am_perm, :]
|
| 119 |
+
am = am[:, :, am_perm]
|
| 120 |
+
img_list = [img_list[i] for i in range(len(img_list)) if not not_animal[i]]
|
| 121 |
+
|
| 122 |
+
# annotate bounding boxes on images
|
| 123 |
+
annotated_image1 = cv2.imread(image1) if image1 else None
|
| 124 |
+
annotated_image2 = cv2.imread(image2) if image2 else None
|
| 125 |
+
for i, ((x1, y1, x2, y2), orig_label, image_path) in enumerate(predictions):
|
| 126 |
+
if image_path == image1:
|
| 127 |
+
annotate_bbox_on_image(annotated_image1, x1, y1, x2, y2, str(perm.index(i)+1))
|
| 128 |
+
else:
|
| 129 |
+
annotate_bbox_on_image(annotated_image2, x1, y1, x2, y2, str(perm.index(i)+1))
|
| 130 |
+
|
| 131 |
+
gallery_images = make_thumbnail_gallery(gallery_images, table_data)
|
| 132 |
+
|
| 133 |
+
# make attention matrix
|
| 134 |
+
img = np.concatenate(img_list, axis=1)
|
| 135 |
+
X, Y, _ = img.shape
|
| 136 |
+
am_img = np.zeros((X+Y, X+Y, 3), dtype=np.uint8)
|
| 137 |
+
if am is not None:
|
| 138 |
+
am_img[:X, X:X+Y] = img
|
| 139 |
+
am_img[X:X+Y, :X] = np.concatenate(img_list, axis=0)
|
| 140 |
+
am_img[X:, X:] = cv2.resize(get_sns_heatmap(am), (Y, Y), interpolation=cv2.INTER_NEAREST)
|
| 141 |
+
|
| 142 |
+
output_image1 = cv2.cvtColor(annotated_image1, cv2.COLOR_BGR2RGB) if image1 else None
|
| 143 |
+
output_image2 = cv2.cvtColor(annotated_image2, cv2.COLOR_BGR2RGB) if image2 else None
|
| 144 |
+
return output_image1, output_image2, gallery_images, am_img
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
with gr.Blocks(css=".block {margin: auto}") as demo:
|
| 148 |
+
args = dict(show_download_button=False, show_fullscreen_button=False) if False else dict()
|
| 149 |
+
with gr.Tab("One image"):
|
| 150 |
+
with gr.Row():
|
| 151 |
+
with gr.Column(scale=1):
|
| 152 |
+
input_image = gr.Image(type="filepath", label="Image")
|
| 153 |
+
path = [x for x in glob(os.path.join(dirname, 'images/gradio_examples/one_image/*')) if x.lower().split(".")[-1] in ["jpg", "jpeg", "png"]]
|
| 154 |
+
examples = gr.Examples(path, input_image)
|
| 155 |
+
btn = gr.Button("Run", variant="primary")
|
| 156 |
+
|
| 157 |
+
with gr.Column(scale=3):
|
| 158 |
+
with gr.Group():
|
| 159 |
+
with gr.Row():
|
| 160 |
+
output_image = gr.Image(type="numpy", label="Annotated Image", scale=16, show_label=False, **args)
|
| 161 |
+
output_image2 = gr.Image(type="numpy", label="Annotated Image 2", scale=0, render=False, show_label=False, **args)
|
| 162 |
+
am_image = gr.Image(type="numpy", label="Attention Map", scale=9, show_label=False, **args)
|
| 163 |
+
with gr.Row():
|
| 164 |
+
output_gallery = gr.Gallery(label="Detected Crops", columns=9, rows=2, height="auto", object_fit='scale-down', show_label=False)
|
| 165 |
+
btn.click(
|
| 166 |
+
fn=show_preds_image,
|
| 167 |
+
inputs=[input_image],
|
| 168 |
+
outputs=[output_image, output_image2, output_gallery, am_image]
|
| 169 |
+
)
|
| 170 |
+
with gr.Tab("Two images"):
|
| 171 |
+
with gr.Row():
|
| 172 |
+
with gr.Column(scale=1):
|
| 173 |
+
input_image = gr.Image(type="filepath", label="Image")
|
| 174 |
+
path2 = [x for x in glob(os.path.join(dirname, 'images/gradio_examples/two_images/*')) if x.lower().split(".")[-1] in ["jpg", "jpeg", "png"]]
|
| 175 |
+
path2.sort()
|
| 176 |
+
examples = gr.Examples(path2, input_image)
|
| 177 |
+
input_image2 = gr.Image(type="filepath", label="Second Image (optional)")
|
| 178 |
+
examples2 = gr.Examples(path2, input_image2)
|
| 179 |
+
btn = gr.Button("Run", variant="primary")
|
| 180 |
+
|
| 181 |
+
with gr.Column(scale=3):
|
| 182 |
+
with gr.Group():
|
| 183 |
+
with gr.Row():
|
| 184 |
+
output_image = gr.Image(type="numpy", label="Annotated Image", scale=4, show_label=False, **args)
|
| 185 |
+
output_image2 = gr.Image(type="numpy", label="Annotated Image 2", scale=4, show_label=False, **args)
|
| 186 |
+
am_image = gr.Image(type="numpy", label="Attention Map", scale=3, show_label=False, **args)
|
| 187 |
+
with gr.Row():
|
| 188 |
+
output_gallery = gr.Gallery(label="Detected Crops", columns=9, rows=2, height="auto", object_fit='scale-down', show_label=False)
|
| 189 |
+
btn.click(
|
| 190 |
+
fn=show_preds_image,
|
| 191 |
+
inputs=[input_image, input_image2],
|
| 192 |
+
outputs=[output_image, output_image2, output_gallery, am_image]
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
demo.launch(allowed_paths=[os.path.join(dirname, '../images/gradio_examples/')])
|
gradio_utils.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
from torch import tensor
|
| 4 |
+
from torchvision.transforms import InterpolationMode, transforms
|
| 5 |
+
import timm
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import cv2
|
| 8 |
+
import numpy as np
|
| 9 |
+
import matplotlib.pyplot as plt
|
| 10 |
+
import seaborn as sns
|
| 11 |
+
from io import BytesIO
|
| 12 |
+
timm.layers.set_fused_attn(False)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def create_text_rectangle(text, width=200, height=40, font=cv2.FONT_HERSHEY_SIMPLEX, color_bgr=(102, 163, 255),
|
| 16 |
+
color_text=(0, 0, 0), text_pad_h=10):
|
| 17 |
+
image = np.full((height, width, 3), color_bgr, dtype=np.uint8)
|
| 18 |
+
font_scale = 1.0
|
| 19 |
+
thickness = 1
|
| 20 |
+
while True:
|
| 21 |
+
(text_width, text_height), _ = cv2.getTextSize(text, font, font_scale, thickness)
|
| 22 |
+
if text_width <= width - 5 and text_height <= height - text_pad_h:
|
| 23 |
+
break
|
| 24 |
+
font_scale -= 0.1
|
| 25 |
+
if font_scale <= 0.1: # Avoid going to zero
|
| 26 |
+
font_scale = 0.1
|
| 27 |
+
break
|
| 28 |
+
x = (width - text_width) // 2
|
| 29 |
+
y = (height + text_height) // 2
|
| 30 |
+
cv2.putText(image, text, (x, y), font, font_scale, color_text, thickness, cv2.LINE_AA)
|
| 31 |
+
return image
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def nms(detections, iou_threshold=0.5):
|
| 35 |
+
if detections is None or len(detections) == 0:
|
| 36 |
+
return detections
|
| 37 |
+
|
| 38 |
+
boxes = detections.xyxy
|
| 39 |
+
scores = detections.conf
|
| 40 |
+
x1, y1, x2, y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
|
| 41 |
+
areas = (x2 - x1) * (y2 - y1)
|
| 42 |
+
order = scores.argsort()[::-1]
|
| 43 |
+
keep = []
|
| 44 |
+
while order.size > 0:
|
| 45 |
+
i = order[0]
|
| 46 |
+
keep.append(i)
|
| 47 |
+
|
| 48 |
+
xx1 = np.maximum(x1[i], x1[order[1:]])
|
| 49 |
+
yy1 = np.maximum(y1[i], y1[order[1:]])
|
| 50 |
+
xx2 = np.minimum(x2[i], x2[order[1:]])
|
| 51 |
+
yy2 = np.minimum(y2[i], y2[order[1:]])
|
| 52 |
+
|
| 53 |
+
w = np.maximum(0.0, xx2 - xx1)
|
| 54 |
+
h = np.maximum(0.0, yy2 - yy1)
|
| 55 |
+
inter = w * h
|
| 56 |
+
|
| 57 |
+
iou = inter / (areas[i] + areas[order[1:]] - inter)
|
| 58 |
+
inds = np.where(iou <= iou_threshold)[0]
|
| 59 |
+
order = order[inds + 1]
|
| 60 |
+
return detections[keep]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
convert = {
|
| 64 |
+
'acinonyxjubatus': 'Cheetah',
|
| 65 |
+
'aepycerosmelampus': 'Impala',
|
| 66 |
+
'alcelaphusbuselaphus': 'Hartebeest',
|
| 67 |
+
'ardeotiskori': 'Kori Bustard',
|
| 68 |
+
'aves': 'Bird',
|
| 69 |
+
'caracalcaracal': 'Caracal',
|
| 70 |
+
'chlorocebuspygerythrus': 'Vervet Monkey',
|
| 71 |
+
'connochaetestaurinus': 'Wildebeest',
|
| 72 |
+
'crocutacrocuta': 'Spotted Hyena',
|
| 73 |
+
'damaliscuslunatusjimela': 'Topi',
|
| 74 |
+
'equusquagga': 'Zebra',
|
| 75 |
+
'eudorcasthomsonii': "Thomson's Gazelle",
|
| 76 |
+
'felislybica': 'African Wildcat',
|
| 77 |
+
'genetta': 'Genets',
|
| 78 |
+
'giraffacamelopardalis': 'Giraffe',
|
| 79 |
+
'herpestidae': 'Mongooses',
|
| 80 |
+
'hippopotamusamphibius': 'Hippopotamus',
|
| 81 |
+
'hyaenahyaena': 'Striped Hyena',
|
| 82 |
+
'hystrixcristata': 'Porcupine',
|
| 83 |
+
'ictonyxstriatus': 'Polecat',
|
| 84 |
+
'kobusellipsiprymnus': 'Waterbuck',
|
| 85 |
+
'leptailurusserval': 'Serval',
|
| 86 |
+
'lepus': 'Hares',
|
| 87 |
+
'loxodontaafricana': 'Elephant',
|
| 88 |
+
'lupulellamesomelas': 'Jackal',
|
| 89 |
+
'madoqua': 'Dik-diks',
|
| 90 |
+
'mellivoracapensis': 'Honey Badger',
|
| 91 |
+
'nangergranti': "Grant's Gazelle",
|
| 92 |
+
'numididae': 'Guineafowl',
|
| 93 |
+
'orycteropusafer': 'Aardvark',
|
| 94 |
+
'otocyonmegalotis': 'Bat-eared Fox',
|
| 95 |
+
'pantheraleo': 'Lion',
|
| 96 |
+
'pantherapardus': 'Leopard',
|
| 97 |
+
'papio': 'Baboons',
|
| 98 |
+
'phacochoerusafricanus': 'Warthog',
|
| 99 |
+
'protelescristatus': 'Aardwolf',
|
| 100 |
+
'redunca': 'Reedbucks',
|
| 101 |
+
'reptilia': 'Reptiles',
|
| 102 |
+
'rhinocerotidae': 'Rhinoceroses',
|
| 103 |
+
'rodentia': 'Rodents',
|
| 104 |
+
'sagittariusserpentarius': 'Secretarybird',
|
| 105 |
+
'struthiocamelus': 'Ostrich',
|
| 106 |
+
'synceruscaffer': 'Buffalo',
|
| 107 |
+
'tragelaphusoryx': 'Eland',
|
| 108 |
+
'tragelaphusscriptus': 'Bushbuck',
|
| 109 |
+
'viverridae': 'Viverrids'
|
| 110 |
+
}
|
| 111 |
+
classes = list(convert.values())
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def cropSquareCV(imagecv, box):
|
| 115 |
+
x1, y1, x2, y2 = box
|
| 116 |
+
xsize = (x2-x1)
|
| 117 |
+
ysize = (y2-y1)
|
| 118 |
+
if xsize > ysize:
|
| 119 |
+
y1 = y1-int((xsize-ysize)/2)
|
| 120 |
+
y2 = y2+int((xsize-ysize)/2)
|
| 121 |
+
if ysize > xsize:
|
| 122 |
+
x1 = x1-int((ysize-xsize)/2)
|
| 123 |
+
x2 = x2+int((ysize-xsize)/2)
|
| 124 |
+
height, width, _ = imagecv.shape
|
| 125 |
+
croppedimagecv = imagecv[max(0, int(y1)): min(int(y2), height), max(0, int(x1)): min(int(x2), width)]
|
| 126 |
+
return croppedimagecv
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
classifier_transforms = transforms.Compose([
|
| 130 |
+
transforms.Resize(size=(182, 182), interpolation=InterpolationMode.BICUBIC, max_size=None, antialias=None),
|
| 131 |
+
transforms.ToTensor(),
|
| 132 |
+
transforms.Normalize(mean=tensor([0.4850, 0.4560, 0.4060]), std=tensor([0.2290, 0.2240, 0.2250]))])
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def get_sns_heatmap(attention_matrix):
|
| 136 |
+
d = attention_matrix.mean(0)
|
| 137 |
+
d_norm = (d - d.min()) / (d.max() - d.min())
|
| 138 |
+
# Plot the heatmap with seaborn
|
| 139 |
+
fig, ax = plt.subplots(figsize=(3, 3), dpi=100)
|
| 140 |
+
sns.heatmap(d_norm, cmap=sns.light_palette("#825f87", as_cmap=True), cbar=False, xticklabels=False, yticklabels=False, ax=ax)
|
| 141 |
+
ax.axis('off')
|
| 142 |
+
# Save the heatmap to a buffer
|
| 143 |
+
buf = BytesIO()
|
| 144 |
+
plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0)
|
| 145 |
+
plt.close(fig)
|
| 146 |
+
# Load the image from the buffer
|
| 147 |
+
buf.seek(0)
|
| 148 |
+
heatmap_img = Image.open(buf).convert("RGB")
|
| 149 |
+
heatmap_np = np.array(heatmap_img)
|
| 150 |
+
return heatmap_np
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def make_thumbnail_gallery(gallery_images, table_data):
|
| 154 |
+
new_gallery = []
|
| 155 |
+
for i in range(len(gallery_images)):
|
| 156 |
+
im = np.concatenate((np.array(gallery_images[i]), create_text_rectangle(table_data[i][1]),
|
| 157 |
+
create_text_rectangle(table_data[i][2], color_bgr=(176, 224, 143))))
|
| 158 |
+
im[:30, :30, :] = create_text_rectangle(str(i+1), 30, 30, color_bgr=(0, 0, 0),
|
| 159 |
+
color_text=(255, 255, 255), text_pad_h=5)
|
| 160 |
+
new_gallery.append(Image.fromarray(im))
|
| 161 |
+
return new_gallery
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def annotate_bbox_on_image(annotated_image, x1, y1, x2, y2, label_text=None):
|
| 165 |
+
height, width, _ = annotated_image.shape
|
| 166 |
+
cv2.rectangle(annotated_image, (x1, y1), (x2, y2), color=(0, 0, 255), thickness=2, lineType=cv2.LINE_AA)
|
| 167 |
+
if label_text:
|
| 168 |
+
fontScale = fontScale = max(0.5, min(width, height) / 2000)
|
| 169 |
+
thickness = 3
|
| 170 |
+
(text_width, text_height), baseline = cv2.getTextSize(label_text, cv2.FONT_HERSHEY_SIMPLEX, fontScale, thickness)
|
| 171 |
+
bg_x1, bg_y1 = x1, max(0, y1 - text_height - baseline - 4)
|
| 172 |
+
bg_x2, bg_y2 = x1 + text_width + 4, y1
|
| 173 |
+
cv2.rectangle(annotated_image, (bg_x1, bg_y1), (bg_x2, bg_y2), (0, 0, 0), -1)
|
| 174 |
+
cv2.putText(annotated_image, label_text, (x1 + 2, y1 - baseline - 2), cv2.FONT_HERSHEY_SIMPLEX,
|
| 175 |
+
fontScale=fontScale, color=(255, 255, 255), thickness=thickness, lineType=cv2.LINE_AA)
|
models.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
import numpy as np
|
| 7 |
+
from functools import partial
|
| 8 |
+
from timm.models.vision_transformer import Block
|
| 9 |
+
import os
|
| 10 |
+
import timm
|
| 11 |
+
timm.layers.set_fused_attn(False)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class BaseModel(nn.Module):
|
| 15 |
+
def get_head_weights(self):
|
| 16 |
+
params = torch.load(os.path.join(os.path.dirname(__file__), "models/crop_classifier_half.pt"), map_location="cpu", weights_only=True)
|
| 17 |
+
params = {k: params[k] for k in ['norm.weight', 'norm.bias', 'head.weight', 'head.bias']}
|
| 18 |
+
self.params = params
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class IndepClassifier(BaseModel):
|
| 22 |
+
def __init__(self, embed_dim=1024):
|
| 23 |
+
super().__init__()
|
| 24 |
+
self.get_head_weights()
|
| 25 |
+
self.head = nn.Linear(self.params["head.weight"].shape[1], self.params["head.weight"].shape[0])
|
| 26 |
+
self.load_state_dict(self.params, strict=False)
|
| 27 |
+
|
| 28 |
+
def forward(self, x):
|
| 29 |
+
x = self.head(x)
|
| 30 |
+
return x
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class MCAClassifier(BaseModel):
|
| 34 |
+
def __init__(self, depth=2, num_heads=8):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.get_head_weights()
|
| 37 |
+
self.embed_dim = self.params["head.weight"].shape[1]
|
| 38 |
+
self.blocks = nn.Sequential(*[Block(dim=self.embed_dim, num_heads=num_heads,
|
| 39 |
+
norm_layer=partial(nn.LayerNorm, eps=1e-6))for i in range(depth)])
|
| 40 |
+
self.norm = nn.LayerNorm(self.embed_dim, eps=1e-6)
|
| 41 |
+
self.num_classes = self.params["head.weight"].shape[0]
|
| 42 |
+
self.head = nn.Linear(self.embed_dim, self.num_classes)
|
| 43 |
+
self.load_state_dict(self.params, strict=False)
|
| 44 |
+
|
| 45 |
+
def forward(self, x):
|
| 46 |
+
x = self.forward_blocks(x)
|
| 47 |
+
x = self.forward_head(x)
|
| 48 |
+
return x
|
| 49 |
+
|
| 50 |
+
def forward_blocks(self, x):
|
| 51 |
+
x = self.blocks(x)
|
| 52 |
+
return x
|
| 53 |
+
|
| 54 |
+
def forward_head(self, x):
|
| 55 |
+
x = self.head(x)
|
| 56 |
+
return x
|
| 57 |
+
|
| 58 |
+
def freeze_head(self):
|
| 59 |
+
self.norm.weight.requires_grad = False
|
| 60 |
+
self.norm.bias.requires_grad = False
|
| 61 |
+
self.head.weight.requires_grad = False
|
| 62 |
+
self.head.bias.requires_grad = False
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
if __name__ == "__main__":
|
| 66 |
+
from utils import crop_to_seq, load_data, filter_df, class_list
|
| 67 |
+
from dataset import Dataset
|
| 68 |
+
|
| 69 |
+
device = "cpu"
|
| 70 |
+
model = MCAClassifier(depth=1)
|
| 71 |
+
model.to(device)
|
| 72 |
+
|
| 73 |
+
df_imgs, scores, embeddings = load_data(os.path.join(os.path.dirname(__file__), "../data/serengeti_toy"))
|
| 74 |
+
df_imgs, df = filter_df(df_imgs, classes=class_list)
|
| 75 |
+
df = crop_to_seq(df_imgs)
|
| 76 |
+
|
| 77 |
+
dataset = Dataset(df, embeddings, class_list, min_seqlength=12, fixed_length=True, nb_synthetic_seq=[1, 2, 3])
|
| 78 |
+
dataloader = torch.utils.data.DataLoader(dataset, batch_size=64, num_workers=1)
|
| 79 |
+
|
| 80 |
+
output_dict = model.predict(dataloader, device)
|
| 81 |
+
print(output_dict["acc"])
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
gradio
|
| 3 |
+
timm
|
| 4 |
+
opencv-python
|
| 5 |
+
ultralytics
|
| 6 |
+
seaborn
|
| 7 |
+
blosc2
|
| 8 |
+
scikit-learn
|
| 9 |
+
wandb
|
| 10 |
+
torchmetrics
|