YOLOX实战:超详细!手把手教你使用YOLOX进行物体检测(附数据集)

网友投稿 1563 2022-05-29

摘要

YOLOX: Exceeding YOLO Series in 2021

代码:https://github.com/Megvii-BaseDetection/YOLOX

论文:https://arxiv.org/abs/2107.08430

YOLOX 是旷视开源的高性能检测器。旷视的研究者将解耦头、数据增强、无锚点以及标签分类等目标检测领域的优秀进展与 YOLO 进行了巧妙的集成组合,提出了 YOLOX,不仅实现了超越 YOLOv3、YOLOv4 和 YOLOv5 的 AP,而且取得了极具竞争力的推理速度。如下图:

其中YOLOX-L版本以 68.9 FPS 的速度在 COCO 上实现了 50.0% AP,比 YOLOv5-L 高出 1.8% AP!还提供了支持 ONNX、TensorRT、NCNN 和 Openvino 的部署版本。

1 配置环境

本机的环境:

1.1 下载源码:

GitHub地址:https://github.com/Megvii-BaseDetection/YOLOX,下载完成后放到D盘根目录,然后用PyCharm打开。

1.2 安装依赖包

点击“Terminal”,如下图,

然后执行下面的命令,安装所有的依赖包。

pip install -r requirements.txt

1

1.3 安装yolox

python setup.py install

1

看到如下信息,则说明安装完成了

1.4 安装apex

APEX是英伟达开源的,完美支持PyTorch框架,用于改变数据格式来减小模型显存占用的工具。其中最有价值的是amp(Automatic Mixed Precision),将模型的大部分操作都用Float16数据类型测试,一些特别操作仍然使用Float32。并且用户仅仅通过三行代码即可完美将自己的训练代码迁移到该模型。实验证明,使用Float16作为大部分操作的数据类型,并没有降低参数,在一些实验中,反而由于可以增大Batch size,带来精度上的提升,以及训练速度上的提升。

安装步骤:

到官网下载apex,地址:mirrors / nvidia / apex · CODE CHINA (csdn.net)

下载完成后,解压后,在Shell里,进入到apex-master中。

执行安装命令

pip install -r requirements.txt python setup.py install

1

2

看到如下log,则表明安装成功。

1.5 安装pycocotools

pip install pycocotools

1

注:如果出现环境问题,可以参考:

Win10 安装pycocotools_AI浩-CSDN博客

1.6 验证环境

下载预训练模型,本文选用的是YOLOX-s,下载地址: https://github.com/Megvii-BaseDetection/YOLOX/releases/download/0.1.1rc0/yolox_s.pth。

下载完成后,将预训练模型放到工程的根目录,如下图:

然后验证环境,执行:

python tools/demo.py image -f exps/default/yolox_s.py -c ./yolox_s.pth --path assets/dog.jpg --conf 0.3 --nms 0.65 --tsize 640 --save_result --device gpu

1

参数说明

查看运行结果:

看到上图说明环境没有问题了。

2 制作数据集

数据集我们采用VOC数据集,原始数据集是Labelme标注的数据集。下载地址:https://download.csdn.net/download/hhhhhhhhhhwwwwwwwwww/14003627。

新建labelme2voc.py文件

import os from typing import List, Any import numpy as np import codecs import json from glob import glob import cv2 import shutil from sklearn.model_selection import train_test_split # 1.标签路径 labelme_path = "LabelmeData/" # 原始labelme标注数据路径 saved_path = "VOC2007/" # 保存路径 isUseTest = True # 是否创建test集 # 2.创建要求文件夹 if not os.path.exists(saved_path + "Annotations"): os.makedirs(saved_path + "Annotations") if not os.path.exists(saved_path + "JPEGImages/"): os.makedirs(saved_path + "JPEGImages/") if not os.path.exists(saved_path + "ImageSets/Main/"): os.makedirs(saved_path + "ImageSets/Main/") # 3.获取待处理文件 files = glob(labelme_path + "*.json") files = [i.replace("\", "/").split("/")[-1].split(".json")[0] for i in files] print(files) # 4.读取标注信息并写入 xml for json_file_ in files: json_filename = labelme_path + json_file_ + ".json" json_file = json.load(open(json_filename, "r", encoding="utf-8")) height, width, channels = cv2.imread(labelme_path + json_file_ + ".jpg").shape with codecs.open(saved_path + "Annotations/" + json_file_ + ".xml", "w", "utf-8") as xml: xml.write('\n') xml.write('\t' + 'WH_data' + '\n') xml.write('\t' + json_file_ + ".jpg" + '\n') xml.write('\t\n') xml.write('\t\tWH Data\n') xml.write('\t\tWH\n') xml.write('\t\tflickr\n') xml.write('\t\tNULL\n') xml.write('\t\n') xml.write('\t\n') xml.write('\t\tNULL\n') xml.write('\t\tWH\n') xml.write('\t\n') xml.write('\t\n') xml.write('\t\t' + str(width) + '\n') xml.write('\t\t' + str(height) + '\n') xml.write('\t\t' + str(channels) + '\n') xml.write('\t\n') xml.write('\t\t0\n') for multi in json_file["shapes"]: points = np.array(multi["points"]) labelName = multi["label"] xmin = min(points[:, 0]) xmax = max(points[:, 0]) ymin = min(points[:, 1]) ymax = max(points[:, 1]) label = multi["label"] if xmax <= xmin: pass elif ymax <= ymin: pass else: xml.write('\t\n') xml.write('\t\t' + labelName + '\n') xml.write('\t\tUnspecified\n') xml.write('\t\t1\n') xml.write('\t\t0\n') xml.write('\t\t\n') xml.write('\t\t\t' + str(int(xmin)) + '\n') xml.write('\t\t\t' + str(int(ymin)) + '\n') xml.write('\t\t\t' + str(int(xmax)) + '\n') xml.write('\t\t\t' + str(int(ymax)) + '\n') xml.write('\t\t\n') xml.write('\t\n') print(json_filename, xmin, ymin, xmax, ymax, label) xml.write('') # 5.复制图片到 VOC2007/JPEGImages/下 image_files = glob(labelme_path + "*.jpg") print("copy image files to VOC007/JPEGImages/") for image in image_files: shutil.copy(image, saved_path + "JPEGImages/") # 6.split files for txt txtsavepath = saved_path + "ImageSets/Main/" ftrainval = open(txtsavepath + '/trainval.txt', 'w') ftest = open(txtsavepath + '/test.txt', 'w') ftrain = open(txtsavepath + '/train.txt', 'w') fval = open(txtsavepath + '/val.txt', 'w') total_files = glob("./VOC2007/Annotations/*.xml") total_files = [i.replace("\", "/").split("/")[-1].split(".xml")[0] for i in total_files] trainval_files = [] test_files = [] if isUseTest: trainval_files, test_files = train_test_split(total_files, test_size=0.15, random_state=55) else: trainval_files = total_files for file in trainval_files: ftrainval.write(file + "\n") # split train_files, val_files = train_test_split(trainval_files, test_size=0.15, random_state=55) # train for file in train_files: ftrain.write(file + "\n") # val for file in val_files: fval.write(file + "\n") for file in test_files: print(file) ftest.write(file + "\n") ftrainval.close() ftrain.close() fval.close() ftest.close()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

运行上面的代码就可以得到VOC2007数据集。如下图所示:

VOC的目录如下,所以要新建data/VOCdevkit目录,然后将上面的结果复制进去

├── data │ ├── VOCdevkit │ │ ├── VOC2007 │ │ │ ├── Annotations #xml文件 │ │ │ ├── JPEGImages #图片 │ │ │ ├── ImageSets │ │ │ │ ├── Main │ │ │ │ │ ├── test.txt │ │ │ │ │ ├── trainval.txt

1

2

3

4

5

6

7

8

9

10

到这里,数据集制作完成。

3 修改数据配置文件

3.1 修改类别

文件路径:exps/example/yolox_voc/yolox_voc_s.py,本次使用的类别有2类,所以将num_classes修改为2。

打开yolox/data/datasets/voc_classes.py文件,修改为自己的类别名:

3.2 修改数据集目录

文件路径:exps/example/yolox_voc/yolox_voc_s.py,data_dir修改为“./data/VOCdevkit”,image_sets删除2012的,最终结果如下:

接着往下翻,修改test的路径,如下图:

打开yolox/data/datasets/voc.py,这里面有个错误。画框位置,将大括号的“%s”去掉,否则验证的时候一直报找不到文件的错误。

修改完成后,执行

python setup.py install

1

重新编译yolox

4 训练

推荐使用命令行的方式训练。

执行命令:

python tools/train.py -f exps/example/yolox_voc/yolox_voc_s.py -d 1 -b 4 --fp16 -c yolox_s.pth

1

就可以开始训练了。如果不喜欢使用命令行的方式,想直接运行train.py,那就需要就如train.py修改参数了。首先把train.py从tools里面复制一份到工程的根目录(建议这样做,否则需要修改的路径比较多,新手容易犯错误),如图:

打开,修改里面的参数。需要修改的参数如下:

parser.add_argument("-b", "--batch-size", type=int, default=4, help="batch size") parser.add_argument( "-d", "--devices", default=1, type=int, help="device for training" ) parser.add_argument( "-f", "--exp_file", default="exps/example/yolox_voc/yolox_voc_s.py", type=str, help="plz input your expriment description file", ) parser.add_argument("-c", "--ckpt", default='yolox_s.pth', type=str, help="checkpoint file") parser.add_argument( "--fp16", dest="fp16", default=True, action="store_true", help="Adopting mix precision training.", )

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

按照上面的参数配置就可以运行了,如下图:

如果训练了一段时间,再想接着以前的模型再训练,应该如何做呢?修改train.py的参数即可,需要修改的参数如下:

parser.add_argument( "--resume", default=True, action="store_true", help="resume training" ) parser.add_argument("-c", "--ckpt", default='YOLOX_outputs/yolox_voc_s/best_ckpt.pth', type=str, help="checkpoint file") parser.add_argument( "-e", "--start_epoch", default=100, type=int, help="resume training start epoch", )

1

2

3

4

5

6

7

8

9

10

11

命令行:

python tools/train.py -f exps/example/yolox_voc/yolox_voc_s.py -d 1 -b 4 -c YOLOX_outputs/yolox_voc_s/latest_ckpt.pth.tar -resume -start_epoch=100

1

2

再次训练,你发现epoch不是从0开始了。

5 测试

修改yolox/data/datasets/_init_.py,导入“VOC_CLASSES”,如下图:

修改tools/demo.py中代码,将“COCO_CLASSES”,改为“VOC_CLASSES”。

将“295”行的Predictor类初始化传入的“COCO_CLASSES”改为“VOC_CLASSES”,如下图:

5.1 单张图片预测

使用训练好的模型进行测试。测试调用tools/demo.py,先用命令行的方式演示:

python tools/demo.py image -f exps/example/yolox_voc/yolox_voc_s.py -c YOLOX_outputs/yolox_voc_s/latest_ckpt.pth --path ./assets/aircraft_107.jpg --conf 0.3 --nms 0.65 --tsize 640 --save_result --device gpu

1

2

运行结果:

如果不想使用命令行,将demo.py复制一份放到工程的根目录,然后修改里面的参数。

parser = argparse.ArgumentParser("YOLOX Demo!") parser.add_argument("-do","--demo", default="image", help="demo type, eg. image, video and webcam") parser.add_argument("-expn", "--experiment-name", type=str, default=None) parser.add_argument("-n", "--name", type=str, default=None, help="model name") parser.add_argument( "--path", default="./assets/aircraft_107.jpg", help="path to images or video" ) # exp file parser.add_argument( "-f", "--exp_file", default="exps/example/yolox_voc/yolox_voc_s.py", type=str, help="pls input your expriment description file", ) parser.add_argument("-c", "--ckpt", default="YOLOX_outputs/yolox_voc_s/best_ckpt.pth", type=str, help="ckpt for eval") parser.add_argument( "--device", default="gpu", type=str, help="device to run our model, can either be cpu or gpu", ) parser.add_argument("--conf", default=0.3, type=float, help="test conf") parser.add_argument("--nms", default=0.45, type=float, help="test nms threshold") parser.add_argument("--tsize", default=640, type=int, help="test img size") parser.add_argument( "--fp16", dest="fp16", default=False, action="store_true", help="Adopting mix precision evaluating.", ) parser.add_argument( "--fuse", dest="fuse", default=False, action="store_true", help="Fuse conv and bn for testing.", )

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

YOLOX实战:超详细!手把手教你使用YOLOX进行物体检测(附数据集)

27

28

29

30

31

32

33

34

35

36

37

38

39

40

然后直接运行demo.py,运行结果如下图:

5.2 批量预测

批量预测很简单,将path参数由文件路径改为图片的文件夹路径就可以。例:

parser.add_argument( "--path", default="./assets", help="path to images or video" )

1

2

3

这样就可以预测assets文件夹下面所有的图片了。

6 保存测试结果

demo.py只有将结果画到图片上,没有保存结果,所以要增加这部分的功能。

打开yolox/utils.visualize.py文件,修改vis方法,将结果返回到上层的方法。

def vis(img, boxes, scores, cls_ids, conf=0.5, class_names=None): result_list = [] for i in range(len(boxes)): box = boxes[i] cls_id = int(cls_ids[i]) score = scores[i] if score < conf: continue x0 = int(box[0]) y0 = int(box[1]) x1 = int(box[2]) y1 = int(box[3]) class_name = class_names[cls_id] one_line = (str(x0), str(y0), str(x1), str(y1), class_name, str(float(score))) str_one_line = " ".join(one_line) result_list.append(str_one_line) color = (_COLORS[cls_id] * 255).astype(np.uint8).tolist() text = '{}:{:.1f}%'.format(class_name, score * 100) txt_color = (0, 0, 0) if np.mean(_COLORS[cls_id]) > 0.5 else (255, 255, 255) font = cv2.FONT_HERSHEY_SIMPLEX txt_size = cv2.getTextSize(text, font, 0.4, 1)[0] cv2.rectangle(img, (x0, y0), (x1, y1), color, 2) txt_bk_color = (_COLORS[cls_id] * 255 * 0.7).astype(np.uint8).tolist() cv2.rectangle( img, (x0, y0 + 1), (x0 + txt_size[0] + 1, y0 + int(1.5 * txt_size[1])), txt_bk_color, -1 ) cv2.putText(img, text, (x0, y0 + txt_size[1]), font, 0.4, txt_color, thickness=1) return img, result_list

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

在demo.py的178行增加获取结果,并返回上层方法,如下图:

然后在182,修改image_demo函数,增加获取结果,保存结果的逻辑,具体代码如下:

def image_demo(predictor, vis_folder, path, current_time, save_result): if os.path.isdir(path): files = get_image_list(path) else: files = [path] files.sort() for image_name in files: outputs, img_info = predictor.inference(image_name) result_image, result_list = predictor.visual(outputs[0], img_info, predictor.confthre) print(result_list) if save_result: save_folder = os.path.join( vis_folder, time.strftime("%Y_%m_%d_%H_%M_%S", current_time) ) os.makedirs(save_folder, exist_ok=True) save_file_name = os.path.join(save_folder, os.path.basename(image_name)) logger.info("Saving detection result in {}".format(save_file_name)) txt_name = os.path.splitext(save_file_name)[0]+".txt" print(txt_name) f = open(txt_name, "w") for line in result_list: f.write(str(line) + '\n') f.close() cv2.imwrite(save_file_name, result_image) ch = cv2.waitKey(0) if ch == 27 or ch == ord("q") or ch == ord("Q"): break

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

然后运行demo.py,就可以将结果保存到txt中。

遇到的错误

1、RuntimeError: DataLoader worker (pid(s) 9368, 12520, 6392, 7384) exited unexpectedly

错误原因:torch.utils.data.DataLoader中的num_workers错误

将num_workers改为0即可,0是默认值。

num_workers是用来指定开多进程的数量,默认值为0,表示不启用多进程。

打开yolox/exp/yolox_base.py,将data_num_workers设置为0,如下图:

将num_workers设置为0,程序报错,并提示设置环境变量KMP_DUPLICATE_LIB_OK=TRUE

那你可以在设置环境变量KMP_DUPLICATE_LIB_OK=TRUE

或者使用临时环境变量:(在代码开始处添加这行代码)

import os os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'

1

2

2、RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR

我执行命令

python tools/train.py -f exps/example/yolox_voc/yolox_voc_s.py -d 1 -b 4 --fp16 -o -c yolox_s.pth.tar

1

报的错误,把-“-o”去掉后就正常了。

python tools/train.py -f exps/example/yolox_voc/yolox_voc_s.py -d 1 -b 4 --fp16 -c yolox_s.pth.tar

1

633818287042)]

将num_workers设置为0,程序报错,并提示设置环境变量KMP_DUPLICATE_LIB_OK=TRUE

那你可以在设置环境变量KMP_DUPLICATE_LIB_OK=TRUE

或者使用临时环境变量:(在代码开始处添加这行代码)

import os os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'

1

2

[外链图片转存中…(img-fPimkIuD-1633818287043)]

2、RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR

我执行命令

python tools/train.py -f exps/example/yolox_voc/yolox_voc_s.py -d 1 -b 4 --fp16 -o -c yolox_s.pth.tar

1

报的错误,把-“-o”去掉后就正常了。

python tools/train.py -f exps/example/yolox_voc/yolox_voc_s.py -d 1 -b 4 --fp16 -c yolox_s.pth.tar

1

机器学习

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:XXL-JOB分布式任务调度平台快速入门
下一篇:【王喆-推荐系统】特征工程篇-(task2)用Spark进行特征处理
相关文章