根据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}")
相关推荐
老金带你玩AI30 分钟前
DeepSeek这次,想把你从AI的监工岗位上解放出来
人工智能
莫西干式秃头1 小时前
用 AI + threejs 写了个浏览器里的 3D 动作游戏《武来》:砍怪、放技能、开 SU7
前端·人工智能·three.js
遇码1 小时前
2026-11-01-daw-retry-banner-body
人工智能·ai·rust·数据分析·大模型·agent
孟健1 小时前
用 WorkBuddy 做个人名片网页,挂上开源设计技能后效果完全不同了
前端·人工智能·ai编程
一点一木1 小时前
🚀 2026 年 10 月 GitHub 十大热门项目排行榜 🔥
人工智能·github
IT_陈寒1 小时前
SpringBoot自动配置的坑,这次终于爬出来了
前端·人工智能·后端
Martina_03211 小时前
AI生成的3D模型打印后沿层纹开裂?用6步检查方向、壁厚与填充
图像处理·人工智能·数学建模·3d·自然语言处理·游戏策划·1024程序员节
极限挑战哥1 小时前
共享电单车联营平台分账架构实践:二清合规与自动分账零人工方案
java·大数据·人工智能·微信小程序·架构·微信公众平台
回眸&啤酒鸭1 小时前
【回眸】Hy4 Preview 多模态内容生成实战指南
人工智能
阿里云大数据AI技术1 小时前
云栖实录|让每一次查询只触达自己的数据:阿里云 Elasticsearch Agent 引擎版重构多租户 AI 搜索基础设施
人工智能