根据txt标签文件在图像上生成真实标签框

一个代码示例

 运行下面代码会在图像上标注出真实标签框。

python 复制代码
import numpy as np
import cv2

images_dir = r'D:/Demo/images2'  # 图像文件夹位置
labels_dir = r'D:/Demo/labels2'  # 标签文件夹位置
output_dir = r'D:/Demo/output'   # 输出文件夹位置

os.makedirs(output_dir, exist_ok=True)

for img_name in os.listdir(images_dir):
    if not img_name.lower().endswith(('.jpg', '.jpeg', '.png')):
        continue

    img_path = os.path.join(images_dir, img_name)
    label_path = os.path.join(labels_dir, os.path.splitext(img_name)[0] + '.txt')

    # 使用 PIL 读取图像(支持中文路径)
    try:
        pil_img = Image.open(img_path).convert('RGB')
        image = np.array(pil_img)
        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
    except Exception as e:
        print(f"无法读取图像: {img_path}, 错误: {e}")
        continue

    h, w = image.shape[:2]

    if not os.path.exists(label_path):
        print(f"未找到标签文件: {label_path}")
        continue

    with open(label_path, 'r', encoding='utf-8') as f:
        for line in f:
            parts = line.strip().split()
            if len(parts) != 5:
                continue
            # class_id = int(parts[0])  # 不需要类别名,可不使用
            x_center = float(parts[1]) * w
            y_center = float(parts[2]) * h
            box_w = float(parts[3]) * w
            box_h = float(parts[4]) * h

            x1 = int(x_center - box_w / 2)
            y1 = int(y_center - box_h / 2)
            x2 = int(x_center + box_w / 2)
            y2 = int(y_center + box_h / 2)

            color = (0, 255, 0)  # 绿色框
            # color = (0, 0, 255)  红色框  需要时把上面那行注释掉,用这行代码
            thickness = 2
            cv2.rectangle(image, (x1, y1), (x2, y2), color, thickness)
            # 注意:这里没有 cv2.putText,所以不会显示 "ship"

    output_path = os.path.join(output_dir, img_name)
    cv2.imwrite(output_path, image)
    print(f"已保存带框图像: {output_path}")
相关推荐
小鹿的周先生几秒前
Spring-AI-第2篇-ChatClient 实战:使用 DeepSeek 完成第一次 AI 对话
java·人工智能·spring
ajassi200014 分钟前
AI语音智能体开发日记(十五)智能体LCD屏幕GIF动画显示方案——从GIF到BMP的完整实战
人工智能·ai·ai编程
Dfreedom.24 分钟前
目标检测后处理核心:NMS非极大值抑制详解
图像处理·人工智能·深度学习·目标检测·目标跟踪
枫叶丹426 分钟前
实时语音 Agent:从语音机器人到连续协作界面
人工智能·chatgpt·机器人·语音识别·agent·codex
戴西软件38 分钟前
戴西iDWS.3DViz Suite数据轻量化可视化软件,从传统桌面软件向云端协同的重大突破
大数据·运维·网络·人工智能·机器学习·3d
AIkk8641 分钟前
2026年AI证件照工具功能速览:三款实用方案对比
人工智能
ReleaseU41 分钟前
Harness + MCP:打通企业工具链的最后一步
人工智能·大模型
衡石科技1 小时前
衡石科技携手超聚变联合发布HENGSHI BOX,引领私域ChatBI规模化落地
大数据·人工智能·科技
新知图书1 小时前
10.4 交互优化与用户体验提升
人工智能·多模态·智能体