YOLO数据标注结果检查(可视化)

在下载一些数据集后,我们需要使用程序将其他格式的数据集转换为YOLO格式的数据集,但是当转换过来的时候不放心,想要可视化标记是否准确,可以直接用下面的代码。

用法就是在终端中输入

python 你的程序名.py --image 图片文件夹路径   --label  标签文件夹路径

代码修改自https://blog.youkuaiyun.com/xiao_9626/article/details/146332133,解决了显示窗口在屏幕外,导致看不到图片。解决显示窗口太大,超出屏幕的情况。 摁空格就可以一直往后检查

import cv2
import argparse
import os
import tkinter as tk

def read_labels(label_path):
    """
    读取YOLO格式的标签文件,返回目标检测框和类别
    :param label_path: 标签文件路径
    :return: list of [class_id, x_center, y_center, width, height]
    """
    boxes = []
    with open(label_path, 'r') as f:
        for line in f.readlines():
            class_id, x_center, y_center, width, height = map(float, line.strip().split())
            boxes.append([class_id, x_center, y_center, width, height])
    return boxes


def draw_boxes(image_path, boxes, class_names):
    """
    在图像上绘制检测框和类别
    :param image_path: 图像路径
    :param boxes: 检测框列表
    :param class_names: 类别名称列表
    """
    image = cv2.imread(image_path)
    height, width, _ = image.shape

    # 获取屏幕的宽度和高度
    root = tk.Tk()
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    root.destroy()

    # 调整窗口大小以适应屏幕
    display_width = min(width, screen_width)
    display_height = min(height, screen_height)

    # 创建窗口并设置窗口大小
    cv2.namedWindow("Image with Bounding Boxes", cv2.WINDOW_NORMAL)
    cv2.resizeWindow("Image with Bounding Boxes", display_width, display_height)

    # 将窗口移动到屏幕左上角
    cv2.moveWindow("Image with Bounding Boxes", 0, 0)

    for box in boxes:
        class_id, x_center, y_center, width_ratio, height_ratio = box
        x_center = int(x_center * width)
        y_center = int(y_center * height)
        box_width = int(width_ratio * width)
        box_height = int(height_ratio * height)

        # 计算左上角和右下角坐标
        x1 = int(x_center - box_width / 2)
        y1 = int(y_center - box_height / 2)
        x2 = int(x_center + box_width / 2)
        y2 = int(y_center + box_height / 2)

        # 绘制矩形框
        cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
        # 添加类别名称
        class_name = class_names[int(class_id)]
        cv2.putText(image, class_name, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

    # 显示图像
    cv2.imshow("Image with Bounding Boxes", image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


def main(image_path, label_path, class_names):
    """
    主函数,处理单个图像和标签
    :param image_path: 图像路径
    :param label_path: 标签路径
    :param class_names: 类别名称列表
    """
    if not os.path.exists(image_path):
        print(f"Error: Image file {image_path} does not exist.")
        return

    if not os.path.exists(label_path):
        print(f"Error: Label file {label_path} does not exist.")
        return

    boxes = read_labels(label_path)
    draw_boxes(image_path, boxes, class_names)


if __name__ == "__main__":
    # 使用 argparse 获取命令行参数
    parser = argparse.ArgumentParser(description="Draw bounding boxes on an image based on YOLO labels.")
    parser.add_argument("--image", type=str, default="data/train/images/0367.jpg",
                        help="Path to the image file. Default is 'default_image.jpg'.")
    parser.add_argument("--label", type=str, default="data/train/labels/0367.txt", help="Path to the label file.")
    args = parser.parse_args()

    # 类别名称列表,根据实际情况修改
    class_names = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
    images_list = []
    labels_list = []
    for root, dirs, files in os.walk(args.image):
        for file in files:
            images_list.append(os.path.join(root, file))
    for root, dirs, files in os.walk(args.label):
        for file in files:
            labels_list.append(os.path.join(root, file))
    for i,v in enumerate(images_list):
        main(v, labels_list[i], class_names)

### 如何实现YOLO数据集可视化 #### 使用Matplotlib和OpenCV进行简单可视化 对于YOLO格式的数据集,可以通过读取图像及其对应的标签文件(.txt),并利用Python中的`matplotlib`库和`opencv-python`库来绘制边界框。 ```python import cv2 import matplotlib.pyplot as plt def plot_bboxes(image_path, label_path): image = cv2.imread(image_path) h, w = image.shape[:2] with open(label_path, 'r') as f: labels = f.readlines() for line in labels: class_id, cx_norm, cy_norm, bw_norm, bh_norm = map(float, line.strip().split()) # Convert normalized coordinates to pixel values. l = int((cx_norm * w) - (bw_norm * w / 2)) r = int((cx_norm * w) + (bw_norm * w / 2)) t = int((cy_norm * h) - (bh_norm * h / 2)) b = int((cy_norm * h) + (bh_norm * h / 2)) color = (0, 255, 0) # Green color for bounding box thickness = 2 # Draw rectangle around object detected by YOLO algorithm image = cv2.rectangle(image, (l, t), (r, b), color, thickness) plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) plt.axis('off') plt.show() ``` 此函数接受一张图片路径以及相应的标签文件路径作为输入参数,并显示带有边框标记的对象位置[^1]。 #### 利用Ultralytics官方提供的工具 来自ultralytics团队开发的YOLOv8版本提供了内置的方法来进行快速而简便的数据集可视化。这不仅限于查看单张图片上的预测结果,还可以帮助理解整个训练过程中的表现情况。 ```python from ultralytics import YOLO model = YOLO('yolov8n.pt') results = model.predict(source='path_to_images_folder', save=True, show_labels=True, conf=0.25) ``` 上述代码片段展示了如何加载预训练模型并对指定文件夹内的所有图片执行推理操作的同时保存带标注的结果图到本地磁盘上[^3]。 #### 使用LabelImg或其他图形化工具 除了编程方式外,还有许多现成的应用程序可以帮助完成这项工作。例如,在创建自定义数据集时经常使用的labelImg就是一个很好的例子。它允许用户通过简单的拖放动作导入图片,并手动添加或调整现有的边界框。此外,该应用程序还支持导出多种不同格式的标注信息,包括但不限于YOLO所需的.txt文件[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值