|
import torch |
|
import pandas as pd |
|
import numpy as np |
|
import gradio as gr |
|
from PIL import Image |
|
from torch.nn import functional as F |
|
from collections import OrderedDict |
|
from torchvision import transforms |
|
from pytorch_grad_cam import GradCAM |
|
from pytorch_grad_cam.utils.image import show_cam_on_image |
|
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget |
|
from pytorch_lightning import LightningModule, Trainer, seed_everything |
|
import albumentations as A |
|
from albumentations.pytorch import ToTensorV2 |
|
import torchvision.transforms as T |
|
from model import YOLOv3 |
|
from train import YOLOTraining |
|
import config |
|
from utils import * |
|
import numpy as np |
|
import cv2 |
|
import albumentations as A |
|
from utils import * |
|
import random |
|
from albumentations.pytorch import ToTensorV2 |
|
|
|
model = YOLOv3(num_classes=config.NUM_CLASSES) |
|
model = YOLOTraining(model) |
|
model.load_state_dict(torch.load("model.pth", map_location=torch.device('cpu')), strict=False) |
|
model.eval() |
|
|
|
def yolo_predict(image: np.ndarray, iou_thresh: float = 0.5, thresh: float = 0.5): |
|
|
|
transforms = A.Compose( |
|
[ |
|
A.LongestMaxSize(max_size=config.IMAGE_SIZE), |
|
A.PadIfNeeded( |
|
min_height=config.IMAGE_SIZE, min_width=config.IMAGE_SIZE, border_mode=cv2.BORDER_CONSTANT |
|
), |
|
A.Normalize(mean=[0, 0, 0], std=[1, 1, 1], max_pixel_value=255,), |
|
ToTensorV2(), |
|
], |
|
) |
|
with torch.no_grad(): |
|
transformed_image = transforms(image=image)["image"].unsqueeze(0).to(config.DEVICE) |
|
output = model(transformed_image) |
|
|
|
bboxes = [[] for _ in range(1)] |
|
for i in range(3): |
|
batch_size, A1, S, _, _ = output[i].shape |
|
anchor = config.SCALED_ANCHORS[i].to(config.DEVICE) |
|
boxes_scale_i = cells_to_bboxes( |
|
output[i].to(config.DEVICE), anchor, S=S, is_preds=True |
|
) |
|
for idx, (box) in enumerate(boxes_scale_i): |
|
bboxes[idx] += box |
|
|
|
nms_boxes = non_max_suppression( |
|
bboxes[0], iou_threshold=iou_thresh, threshold=thresh, box_format="midpoint", |
|
) |
|
plot_img = draw_predictions(image, nms_boxes, class_labels=config.PASCAL_CLASSES) |
|
|
|
return [plot_img] |
|
|
|
|
|
def draw_predictions(image: np.ndarray, boxes: list[list], class_labels: list[str]) -> np.ndarray: |
|
"""Plots predicted bounding boxes on the image""" |
|
|
|
colors = [[random.randint(0, 255) for _ in range(3)] for name in class_labels] |
|
|
|
im = np.array(image) |
|
height, width, _ = im.shape |
|
bbox_thick = int(0.6 * (height + width) / 600) |
|
|
|
|
|
for box in boxes: |
|
assert len(box) == 6, "box should contain class pred, confidence, x, y, width, height" |
|
class_pred = box[0] |
|
conf = box[1] |
|
box = box[2:] |
|
upper_left_x = box[0] - box[2] / 2 |
|
upper_left_y = box[1] - box[3] / 2 |
|
|
|
x1 = int(upper_left_x * width) |
|
y1 = int(upper_left_y * height) |
|
|
|
x2 = x1 + int(box[2] * width) |
|
y2 = y1 + int(box[3] * height) |
|
|
|
cv2.rectangle( |
|
image, |
|
(x1, y1), (x2, y2), |
|
color=colors[int(class_pred)], |
|
thickness=bbox_thick |
|
) |
|
text = f"{class_labels[int(class_pred)]}: {conf:.2f}" |
|
t_size = cv2.getTextSize(text, 0, 0.7, thickness=bbox_thick // 2)[0] |
|
c3 = (x1 + t_size[0], y1 - t_size[1] - 3) |
|
|
|
cv2.rectangle(image, (x1, y1), c3, colors[int(class_pred)], -1) |
|
cv2.putText( |
|
image, |
|
text, |
|
(x1, y1 - 2), |
|
cv2.FONT_HERSHEY_SIMPLEX, |
|
0.7, |
|
(0, 0, 0), |
|
bbox_thick // 2, |
|
lineType=cv2.LINE_AA, |
|
) |
|
|
|
return image |
|
|
|
demo = gr.Interface( |
|
fn=yolo_predict, |
|
inputs=[ |
|
gr.Image(shape=(config.IMAGE_SIZE,config.IMAGE_SIZE), label="Input Image"), |
|
gr.Slider(0, 1, value=0.5, step=0.05, label="IOU Threshold"), |
|
gr.Slider(0, 1, value=0.5, step=0.05, label="Threshold") |
|
], |
|
outputs=gr.Gallery(rows=1, columns=1), |
|
examples=[ |
|
["examples/000001.jpg", 0.5, 0.5], |
|
["examples/000002.jpg", 0.5, 0.5], |
|
["examples/000003.jpg", 0.5, 0.5], |
|
["examples/000004.jpg", 0.5, 0.5], |
|
["examples/000005.jpg", 0.5, 0.5], |
|
["examples/000006.jpg", 0.5, 0.5], |
|
["examples/000007.jpg", 0.5, 0.5], |
|
["examples/000008.jpg", 0.5, 0.5], |
|
["examples/000009.jpg", 0.5, 0.5], |
|
["examples/000010.jpg", 0.5, 0.5] |
|
] |
|
) |
|
|
|
demo.launch() |