【目标检测】使用YOLO格式标注将目标框中的图片截取保存

该Python脚本用于读取包含目标框信息的txt文件,根据标注数据截取图片中的目标区域,然后按照类别保存到不同的文件夹,用于后续的分类网络训练。它支持YOLOv5格式的坐标转换,并能处理jpg、jpeg和png格式的图像。
摘要由CSDN通过智能技术生成

将目标框中的图片截取保存到文件夹中用于分类网络训练。

Python代码:

import os
import cv2

"""
|-----------------------------------------------|
| index |           class           | new label |
|-----------------------------------------------|
|   0   | Class 1                   |  label 1  |
|   1   | Class 2                   |  label 2  |
|   2   | Class 3                   |  label 3  |
|-----------------------------------------------|
"""

# 指定图片文件夹路径和txt文件夹路径
img_folder = "images"
txt_folder = "labels"

# 遍历图片文件夹中的所有文件
for filename in os.listdir(img_folder):
    # 确保文件是一个图像文件
    if filename.endswith(".jpg") or filename.endswith(".jpeg") or filename.endswith(".png"):
        # 构造图像文件路径
        image_file_path = os.path.join(img_folder, filename)

        # 构造对应的txt文件路径
        txt_filename = os.path.splitext(filename)[0] + ".txt"
        label_file_path = os.path.join(txt_folder, txt_filename)

        # 读取标注文件和原始图片
        with open(label_file_path, 'r') as f:
            lines = f.readlines()
        image = cv2.imread(image_file_path)

        # 循环处理每个标注框
        i = 0
        for line in lines:
            i = i + 1
            class_id, x_center, y_center, width, height = map(float, line.strip().split())

            # 将YOLOv5格式的坐标转换为常规坐标
            left = int((x_center - width / 2) * image.shape[1])
            top = int((y_center - height / 2) * image.shape[0])
            right = int((x_center + width / 2) * image.shape[1])
            bottom = int((y_center + height / 2) * image.shape[0])

            class_id = int(class_id)

            if class_id == 0:
                folder = 'label 1'
            elif class_id == 1:
                folder = 'label 2'
            elif class_id == 2:
                folder = 'label 3'

            # 截取标注框内的内容并保存为新图片
            object_image = image[top:bottom, left:right]
            object_file_path = image_file_path.split("\\")
            object_file_path = f"{folder}/" + os.path.splitext(object_file_path[1])[0] + f"_{int(class_id)}_{i}.jpg"
            print(object_file_path)
            cv2.imwrite(object_file_path, object_image)

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值