根据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}")
相关推荐
K姐研究社9 小时前
怎么用AI制作电商口播视频,开拍APP一键生成
人工智能·音视频
LaughingZhu9 小时前
Product Hunt 每日热榜 | 2026-05-21
前端·人工智能·经验分享·chatgpt·html
传说故事10 小时前
【论文阅读】MotuBrain: An Advanced World Action Model for Robot Control
论文阅读·人工智能·具身智能·wam
北京耐用通信10 小时前
全域适配工业场景耐达讯自动化Modbus TCP 转 PROFIBUS 网关轻松实现以太网与现场总线互通
网络·人工智能·网络协议·自动化·信息与通信
火山引擎开发者社区10 小时前
TRAE × 火山引擎 Supabase:为你的 AI 应用装上“数据引擎”
人工智能
小a彤11 小时前
GE 在 CANN 五层架构中的位置
人工智能·深度学习·transformer
前端若水11 小时前
会话管理:创建、切换、删除对话历史
前端·人工智能·python·react.js
Upsy-Daisy11 小时前
AI Agent 项目学习笔记(八):Tool Calling 工具调用机制总览
人工智能·笔记·学习
企学宝11 小时前
企学宝5月专题课程丨《OpenClaw AI 智能体实战营:从零基础部署到全场景自动化落地》
人工智能·ai·企业培训
冬奇Lab12 小时前
让 AI Agent 更可靠:Harness Engineering 与多 Agent 系统工程实践
人工智能·llm·agent