根据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}")
相关推荐
IT_陈寒2 分钟前
Vite的热更新突然不香了,排查三小时差点砸键盘
前端·人工智能·后端
阿里云大数据AI技术2 小时前
构建高转化海外电商搜索:阿里云OpenSearch行业算法版的全链路智能优化策略实战
人工智能·搜索引擎
Awu12272 小时前
⚡从零开发 Agent CLI(五)实现一个可治理、可扩展的工具系统
前端·人工智能·claude
字节跳动视频云技术团队2 小时前
让 Agent 成为音视频工作台:AI MediaKit CLI + Skill 发布
人工智能·音视频开发
魏祖潇2 小时前
framework 整合实战——DDD/TDD/SDD 三件套在 framework 仓的真实落地
人工智能·后端
Token炼金师3 小时前
去噪扩散:从随机噪声到高保真图像的数学之路
人工智能·aigc
这个DBA有点耶3 小时前
AI写的SQL跑崩了生产库,这锅谁背?
数据库·人工智能·程序员
阿里云大数据AI技术3 小时前
阿里云 EMR AI 助手正式发布:从问答工具到全栈智能运维助手
运维·人工智能
Larcher4 小时前
从零搭建 MCP 服务——让 AI 拥有无限扩展能力
人工智能·程序员
zzzzzz3104 小时前
你的 AI 写的 React 烂透了?这个 8000+ Star 的开源工具能揪出 90% 的「Agent 屎山」
人工智能