likes
comments
collection
share

Labelimg标注自己的数据集,及如何划分训练集和验证集,应用于Yolov5

作者站长头像
站长
· 阅读数 20

用来标注数据的工具,其实有不少,但是最好入门,我个人觉得还是这个labelimg工具最简单。 我标注的是关于救生圈的数据集作为案例,数据量不大,主要是为了方便讲述。

一、前期工作

1.1、创建相关文件夹

Labelimg标注自己的数据集,及如何划分训练集和验证集,应用于Yolov5

predfined_class.txt 是存放我们标签的文本文件,内容如下:

Labelimg标注自己的数据集,及如何划分训练集和验证集,应用于Yolov5

1.2、准备数据

案例数据都是从 pexels 网站所下载的。

Labelimg标注自己的数据集,及如何划分训练集和验证集,应用于Yolov5

全部放在 JPEGImages 文件夹下。

Labelimg标注自己的数据集,及如何划分训练集和验证集,应用于Yolov5

下载下来的时候,大概率全部是无序号的名称,不方便,我的建议是重命名为统一的名称。 可以用下面这段代码来进行重命名:

Labelimg标注自己的数据集,及如何划分训练集和验证集,应用于Yolov5

import os  
  
def rename(path):  
i = 0  
# '该文件夹下所有的文件(包括文件夹)'  
FileList = os.listdir(path)  
# '遍历所有文件'  
for files in FileList:  
# '原来的文件路径'  
oldDirPath = os.path.join(path, files)  
# '如果是文件夹则递归调用'  
if os.path.isdir(oldDirPath):  
rename(oldDirPath)  
# '文件名'  
fileName = os.path.splitext(files)[0]  
# '文件扩展名'  
fileType = os.path.splitext(files)[1]  
# '新的文件路径'  
newDirPath = os.path.join(path, str(i) + fileType)  
# '重命名'  
os.rename(oldDirPath, newDirPath)  
i += 1  
  
path = 'F://python_project//yolov5_project//yolov5-6.1-blog-demo//mydatasets//VOCdevkit//VOC2007//JPEGImages//'  
rename(path)

二、安装 labelImg

pip install labelimg -i <https://pypi.tuna.tsinghua.edu.cn/simple>

Labelimg标注自己的数据集,及如何划分训练集和验证集,应用于Yolov5

使用:

labelimg JPEGImages predefined_classes.txt

执行完后会让你选择一个文件夹,这里选择的文件夹是用来保存标签文件的。 我们选择 Annotations 文件夹即可。

Labelimg标注自己的数据集,及如何划分训练集和验证集,应用于Yolov5

但是在标注的时候会闪退,然后报下面的错误。

2.1、labelImg报错:TypeError: setValue(self, int): argument 1 has unexpected type ‘float‘,打开后闪退

如果本机电脑环境不是python3.9,在使用 labelimg的时候,可能会出现这个错误,打开图片后闪退。

具体怎么用在后文。

Labelimg标注自己的数据集,及如何划分训练集和验证集,应用于Yolov5

打开图片后,立马就闪退啦。

具体原因:python 版本不匹配,我的本机python环境为 3.10,而labelImg需要的python 版本为3.9

解决方案也很简单,直接使用换用 conda 重新建立一个新的环境:(没有conda,建议去安装一个,我觉得是必需品)

conda create -n base_python_3.9 python=3.9 #创建一个python为3.9版本的环境

conda activate base_python_3.9 # 激活创建的环境

pip install labelimg -i https://pypi.tuna.tsinghua.edu.cn/simple

Labelimg标注自己的数据集,及如何划分训练集和验证集,应用于Yolov5 等待下载完,然后激活这个环境

Labelimg标注自己的数据集,及如何划分训练集和验证集,应用于Yolov5

cd 到 JPEGImages目录层级 Labelimg标注自己的数据集,及如何划分训练集和验证集,应用于Yolov5

重新打开 labelImg 即可。

labelimg JPEGImages predefined_classes.txt

弹出来的文件夹是让你选择保存标注文件的位置,没选对,进去界面也可以更改保存路径的,没有关系

Labelimg标注自己的数据集,及如何划分训练集和验证集,应用于Yolov5

三、如何使用 labelimg

还是上面那张图,我们来标注一下各个按钮的作用吧。 Labelimg标注自己的数据集,及如何划分训练集和验证集,应用于Yolov5

保存格式还可以直接保存为yolo格式的数据集。 一些快捷使用方式: 1、W 是进行标注 2、A 是切换到上一张图片 3、D 是切换到下一张图片 想写好像也没啥能写的啊 开始实践吧

Labelimg标注自己的数据集,及如何划分训练集和验证集,应用于Yolov5

全部标注完后 Labelimg标注自己的数据集,及如何划分训练集和验证集,应用于Yolov5 按照这个方式就一直把图片标完就OK啦。 标注好的文件,会在我们之前选中的文件夹中出现,我们现在选择的数据格式为 VOC,是xml形式的 如下:

Labelimg标注自己的数据集,及如何划分训练集和验证集,应用于Yolov5

四、VOC 数据格式转化为Yolo格式,并划分训练集和验证集

我们标注的VOC的数据,但实际上我们要应用到yolo上面的,所以需要做一个数据转换,你如果直接选择的是Yolo格式的话,只需要进行划分就可以。

import xml.etree.ElementTree as ET  
import pickle  
import os  
from os import listdir, getcwd  
from os.path import join  
import random  
from shutil import copyfile  
  
classes = ["life_buoy"]  
  
TRAIN_RATIO = 80  
  
def clear_hidden_files(path):  
    dir_list = os.listdir(path)  
    for i in dir_list:  
    abspath = os.path.join(os.path.abspath(path), i)  
    if os.path.isfile(abspath):  
    if i.startswith("._"):  
    os.remove(abspath)  
    else:  
    clear_hidden_files(abspath)  
  
def convert(size, box):  
    dw = 1./size[0]  
    dh = 1./size[1]  
    x = (box[0] + box[1])/2.0  
    y = (box[2] + box[3])/2.0  
    w = box[1] - box[0]  
    h = box[3] - box[2]  
    x = x*dw  
    w = w*dw  
    y = y*dh  
    h = h*dh  
    return (x,y,w,h)  
  
def convert_annotation(image_id):  
    in_file = open('VOCdevkit/VOC2007/Annotations/%s.xml' %image_id)  
    out_file = open('VOCdevkit/VOC2007/YOLOLabels/%s.txt' %image_id, 'w')  
    tree=ET.parse(in_file)  
    root = tree.getroot()  
    size = root.find('size')  
    w = int(size.find('width').text)  
    h = int(size.find('height').text)  
  
    for obj in root.iter('object'):  
    difficult = obj.find('difficult').text  
    cls = obj.find('name').text  
    if cls not in classes or int(difficult) == 1:  
    continue  
    cls_id = classes.index(cls)  
    xmlbox = obj.find('bndbox')  
    b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))  
    bb = convert((w,h), b)  
    out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')  
    in_file.close()  
    out_file.close()  
  
wd = os.getcwd()  
wd = os.getcwd()  
data_base_dir = os.path.join(wd, "VOCdevkit/")  
if not os.path.isdir(data_base_dir):  
    os.mkdir(data_base_dir)  
work_sapce_dir = os.path.join(data_base_dir, "VOC2007/")  
if not os.path.isdir(work_sapce_dir):  
    os.mkdir(work_sapce_dir)  
annotation_dir = os.path.join(work_sapce_dir, "Annotations/")  
if not os.path.isdir(annotation_dir):  
    os.mkdir(annotation_dir)  
clear_hidden_files(annotation_dir)  
image_dir = os.path.join(work_sapce_dir, "JPEGImages/")  
if not os.path.isdir(image_dir):  
os.mkdir(image_dir)  
clear_hidden_files(image_dir)  
yolo_labels_dir = os.path.join(work_sapce_dir, "YOLOLabels/")  
if not os.path.isdir(yolo_labels_dir):  
    os.mkdir(yolo_labels_dir)  
clear_hidden_files(yolo_labels_dir)  
yolov5_images_dir = os.path.join(data_base_dir, "images/")  
if not os.path.isdir(yolov5_images_dir):  
    os.mkdir(yolov5_images_dir)  
clear_hidden_files(yolov5_images_dir)  
yolov5_labels_dir = os.path.join(data_base_dir, "labels/")  
if not os.path.isdir(yolov5_labels_dir):  
    os.mkdir(yolov5_labels_dir)  
clear_hidden_files(yolov5_labels_dir)  
yolov5_images_train_dir = os.path.join(yolov5_images_dir, "train/")  
if not os.path.isdir(yolov5_images_train_dir):  
    os.mkdir(yolov5_images_train_dir)  
clear_hidden_files(yolov5_images_train_dir)  
yolov5_images_test_dir = os.path.join(yolov5_images_dir, "val/")  
if not os.path.isdir(yolov5_images_test_dir):  
    os.mkdir(yolov5_images_test_dir)  
clear_hidden_files(yolov5_images_test_dir)  
yolov5_labels_train_dir = os.path.join(yolov5_labels_dir, "train/")  
if not os.path.isdir(yolov5_labels_train_dir):  
    os.mkdir(yolov5_labels_train_dir)  
clear_hidden_files(yolov5_labels_train_dir)  
yolov5_labels_test_dir = os.path.join(yolov5_labels_dir, "val/")  
if not os.path.isdir(yolov5_labels_test_dir):  
    os.mkdir(yolov5_labels_test_dir)  
clear_hidden_files(yolov5_labels_test_dir)  
  
train_file = open(os.path.join(wd, "yolov5_train.txt"), 'w')  
test_file = open(os.path.join(wd, "yolov5_val.txt"), 'w')  
train_file.close()  
test_file.close()  
train_file = open(os.path.join(wd, "yolov5_train.txt"), 'a')  
test_file = open(os.path.join(wd, "yolov5_val.txt"), 'a')  
list_imgs = os.listdir(image_dir) # list image files  
prob = random.randint(1, 100)  
print("Probability: %d" % prob)  
for i in range(0,len(list_imgs)):  
    path = os.path.join(image_dir,list_imgs[i])  
    if os.path.isfile(path):  
        image_path = image_dir + list_imgs[i]  
        voc_path = list_imgs[i]  
        (nameWithoutExtention, extention) = os.path.splitext(os.path.basename(image_path))  
        (voc_nameWithoutExtention, voc_extention) = os.path.splitext(os.path.basename(voc_path))  
        annotation_name = nameWithoutExtention + '.xml'  
        annotation_path = os.path.join(annotation_dir, annotation_name)  
        label_name = nameWithoutExtention + '.txt'  
        label_path = os.path.join(yolo_labels_dir, label_name)  
    prob = random.randint(1, 100)  
    print("Probability: %d" % prob)  
if(prob < TRAIN_RATIO): # train dataset  
    if os.path.exists(annotation_path):  
        train_file.write(image_path + '\n')  
        convert_annotation(nameWithoutExtention) # convert label  
        copyfile(image_path, yolov5_images_train_dir + voc_path)  
        copyfile(label_path, yolov5_labels_train_dir + label_name)  
else: # test dataset  
    if os.path.exists(annotation_path):  
        test_file.write(image_path + '\n')  
        convert_annotation(nameWithoutExtention) # convert label  
        copyfile(image_path, yolov5_images_test_dir + voc_path)  
        copyfile(label_path, yolov5_labels_test_dir + label_name)  
train_file.close()  
test_file.close()

运行后是这样的一个效果: Labelimg标注自己的数据集,及如何划分训练集和验证集,应用于Yolov5

images/train 为训练集,images/val为验证集,label/train、val 则是为我们的标注文件,YOLOLables 文件夹下则是为全部的标注文件文件。 Labelimg标注自己的数据集,及如何划分训练集和验证集,应用于Yolov5

这么看你可能会更清楚一些。

不知道看到这里,你是否已经对标注数据有所了解,如果仍然对这一切感觉到好奇的话,可以阅读相关的文章或视频,进行学习,以便于更好的理解这些。

最后

系列的第二篇文章也终于可以在博客上呈现出来啦,那么下一篇就是讲述如何使用Yolov5 训练自己的数据集,测试看看我们自己训练的数据集,训练出来的效果是如何的啦。 那我们就一起期待着下一篇的博客的相遇吧

转载自:https://juejin.cn/post/7274789845754183715
评论
请登录