show_annotations.py
Python script, ASCII text executable
1import os 2import time 3from os import path 4 5import cv2 as cv 6import numpy as np 7from PIL import Image, ImageFont, ImageDraw 8 9import matplotlib.pyplot as plt 10import matplotlib.patches as patches 11 12import math 13 14font = ImageFont.truetype("/home/vlad/.local/share/fonts/Roboto-Medium.ttf", 12) 15 16image_path = "./yolo_data/IMG-20240514-WA0087.jpg" 17assert path.exists(image_path), f"Image {image_path} not found" 18from ruamel.yaml import YAML 19 20yaml = YAML() 21 22with open("yolo.yaml", "r") as file: 23data = yaml.load(file) 24class_mapping = data["names"] 25 26img = cv.imread(image_path) 27annotations_file = path.splitext(image_path)[0] + ".txt" 28with open(annotations_file, "r") as f: 29annotations = [] 30for line in f: 31klass, cx, cy, w, h = line.split() 32annotations.append((int(klass), float(cx), float(cy), float(w), float(h))) 33 34for box in annotations: 35# Get coordinates and draw the bounding box 36klass, cx, cy, w, h = box 37x1 = int((cx - w / 2) * img.shape[1]) 38y1 = int((cy - h / 2) * img.shape[0]) 39x2 = int((cx + w / 2) * img.shape[1]) 40y2 = int((cy + h / 2) * img.shape[0]) 41 42cv.rectangle(img, (x1, y1), (x2, y2), (255, 255, 255), 2) 43cv.rectangle(img, (x1 - 1, y1 - 1), (x2 + 1, y2 + 1), (0, 152, 255), 2) 44 45cls = int(klass) 46 47img_pil = Image.fromarray(img) 48draw = ImageDraw.Draw(img_pil) 49 50draw.text((x1, y1), 51f"[VAL] {class_mapping[cls]}", 52font=font, 53fill=(255, 255, 255), 54stroke_width=1, 55stroke_fill=(0, 0, 0)) 56img = np.array(img_pil) 57 58result = cv.imwrite("./annotated.jpg", img) 59assert result, "Failed to save image" 60assert path.exists("./annotated.jpg"), "Failed to save image" 61