标注工具:LabelImg
下载方法:
1.CMD中输入下边代码
pip install labelimg -i https://pypi.tuna.tsinghua.edu.cn/simple
作者使用Opencv+python脚本进行拍摄,要使用务必先安装Opencv
import cv2
import os
print("=============================================")
print("= 热键(请在摄像头的窗口使用): =")
print("= z: 更改存储目录 =")
print("= x: 拍摄图片 =")
print("= q: 退出 =")
print("=============================================")
print()
class_name = input("请输入存储目录:")
while os.path.exists(class_name):
class_name = input("目录已存在!请输入存储目录:")
os.mkdir(class_name)
index = 1
cap = cv2.VideoCapture(0)
width = 1280
height = 720
w = 720
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
crop_w_start = (width - w) // 2
crop_h_start = (height - w) // 2
print(width, height)
while True:
# get a frame
ret, frame = cap.read()
# show a frame
frame = frame[crop_h_start:crop_h_start + w, crop_w_start:crop_w_start + w]
frame = cv2.flip(frame, 1, dst=None)
cv2.imshow("capture", frame)
input = cv2.waitKey(1) & 0xFF
if input == ord('z'):
class_name = input("请输入存储目录:")
while os.path.exists(class_name):
class_name = input("目录已存在!请输入存储目录:")
os.mkdir(class_name)
elif input == ord('x'):
cv2.imwrite("%s/%d.jpeg" % (class_name, index),
cv2.resize(frame, (224, 224), interpolation=cv2.INTER_AREA))
print("%s: %d 张图片" % (class_name, index))
index += 1
if input == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
数据集照片要点:
1、数量!!!!这个是关键,尽可能多,作者所使用yolov5s模型(主要是显卡带不动别的),至少要在100张以上才能让识别率提升到可用
2、样本尽可能多样化,手势正面,侧面、背面,有光、无光、本人的、别人的,总之你能想到越多不一样的样本,你的识别率越高.
首先准备下VOC格式数据集的文件夹
├── VOC2007
│├── JPEGImages 存放需要打标签的图片文件
│├── Annotations 存放标注的标签文件
│├──ImageSets 存放测试集与训练集列表的文件夹
打开lableimg后把打开图片的文件路径设置成JPEGImages,标签存储路径改成Annotations,打开设置开启自动保存
接下来尝试开始标注:
常用的快捷键:w启用标注,d下一张,s保存
标注时需要注意
1、务必尽可能地把贴住你所想要识别的物体,减少背景的干扰,最好背景占比低于30%,否则会导致在不一样的背景难以识别的情况
2、可以准备几张空白的背景图作为负样本,不需要标注,直接跳过,最后新建几个空标签文件就行。
标注界面:
生成标签文件:
LabelImg生成的文件不能直接使用,要进行中心化转化
代码如下,需要注意的是,classes那里要改成你要训练的目标名称,一定要与你标注时用的名字一样,大小写都不能错
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
import shutil
sets=[('TrainVal', 'train'), ('TrainVal', 'val')]
classes = ["cheng"]
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(year, image_set, image_id):
in_file = open('VOC%s/Annotations/%s.xml'%(year, image_id),'rb')
out_file = open('VOC%s/labels/%s_%s/%s.txt'%(year, year, image_set, 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')
def copy_images(year,image_set, image_id):a
in_file = 'VOC%s/JPEGImages/%s.jpg'%(year, image_id)
out_flie = 'VOC%s/images/%s_%s/%s.jpg'%(year, year, image_set, image_id)
shutil.copy(in_file, out_flie)
wd = getcwd()
for year, image_set in sets:
if not os.path.exists('VOC%s/labels/%s_%s'%(year,year, image_set)):
os.makedirs('VOC%s/labels/%s_%s'%(year,year, image_set))
if not os.path.exists('VOC%s/images/%s_%s'%(year,year, image_set)):
os.makedirs('VOC%s/images/%s_%s'%(year,year, image_set))
image_ids = open('VOC%s/ImageSets/Main/%s.txt'%(year, image_set)).read().strip().split()
list_file = open('VOC%s/%s_%s.txt'%(year, year, image_set), 'w')
for image_id in image_ids:
list_file.write('%s/VOC%s/images/%s_%s/%s.jpeg\n'%(wd, year, year, image_set, image_id))
convert_annotation(year, image_set, image_id)
copy_images(year, image_set, image_id)
list_file.close()
归一化完成之后,要进行训练集与测试集的分类,代码如下:
import os
import random
xmlfilepath = "VOCTrainval/Annotations" # xml文件的路径
saveBasePath = "VOCTrainVal/ImageSets/" # 生成的txt文件的保存路径
trainval_percent = 0.85 # 训练验证集占整个数据集的比重(划分训练集和测试验证集)
train_percent = 0.7 # 训练集占整个训练验证集的比重(划分训练集和验证集)
total_xml = os.listdir(xmlfilepath)
num = len(total_xml)
list = range(num)
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
trainval = random.sample(list, tv)
train = random.sample(trainval, tr)
print("train and val size", tv)
print("traub suze", tr)
ftrainval = open(os.path.join(saveBasePath, 'Main/trainval.txt'), 'w')
ftest = open(os.path.join(saveBasePath, 'Main/test.txt'), 'w')
ftrain = open(os.path.join(saveBasePath, 'Main/train.txt'), 'w')
fval = open(os.path.join(saveBasePath, 'Main/val.txt'), 'w')
for i in list:
name = total_xml[i][:-4] + '\n'
if i in trainval:
ftrainval.write(name)
if i in train:
ftrain.write(name)
else:
fval.write(name)
else:
ftest.write(name)
ftrainval.close()
ftrain.close()
fval.close()
ftest.close()
其中训练集比重与测试集比重,将直接影响你的实验结果,可以根据你的数据集进行调整比例。
代码运行完成后,我们将可以看到voc文件夹整体框架如下:
到这一步基本上,数据集就准备好了,但不是完了,你会根据你一次次训练的结果,测试的结果,看看缺陷在哪,会补充很多很多东西。我计划1000张照片解决,结果增增改改到了1700真的非常头疼。