Darknet ROS下的食品分类

初期成果:

配置Darknet_ROS

1.创建工作空间并下载darknet_ros

根据Darknet ROS项目文档的介绍:

This is a ROS package developed for object detection in camera images. You only look once (YOLO) is a state-of-the-art, real-time object detection system. In the following ROS package you are able to use YOLO (V3) on GPU and CPU. The pre-trained model of the convolutional neural network is able to detect pre-trained classes including the data set from VOC and COCO, or you can also create a network with your own detection objects. For more information about YOLO, Darknet, available training data and training YOLO see the following link: YOLO: Real-Time Object Detection.

The YOLO packages have been tested under ROS Noetic and Ubuntu 20.04. Note: We also provide branches that work under ROS Melodic, ROS Foxy and ROS2.This is research code, expect that it changes often and any fitness for a particular purpose is disclaimed.

​ 了解到这是一个为ROS下的利用darknet进行目标检测的功能包,特点是可以自定义用于目标检测的订阅话题,同时通过三个话题发布classes和bounding box等信息,可以实现实时的视频流的目标检测和分类;而这个项目一直在更新,为了保证下述操作可以复现,可以从百度云盘:https://pan.baidu.com/s/1_ddm3U_KKWDvGCtpL2ZGrg(提取码:1234)下载,需要注意的是直接下载的darknet_ros下是darknet文件夹是空的,可以从百度网盘:https://pan.baidu.com/s/1J-xWuHGqBUNoPvL2qpLfjQ(提取码:1234)下载darknet,***将darknet_ros下的darknet替换***。

将完整的darknet_ros下放到yolo_detect工作空间的src目录下

在前面的操作完成后

2.下载预训练权重

访问
pjreddie.com/media/files/yolov2.weights
pjreddie.com/media/files/yolov2-tiny.weights
pjreddie.com/media/files/yolov3.weights

下载预训练权重放到yolo_detect/src/darknet_ros/darknet_ros/yolo_network_config/weights文件夹下

1
2
cd ~/yolo_detect
catkin_make -DCMAKE_BUILD_TYPE=Release
这里除了有关具体训练配置和检测配置文件还没修改,已经完成了darknet_ros的配置!!!

制作数据集

1.从/camera/color/image_raw采集数据集

Kinetc相机节点启动后,

rqt_image_view /camera/color/image_raw

这样就可以一张张存,缺点就是命名麻烦,这样最后有100张png

这里曾经尝试写一个节点订阅/camera/color/image_raw,键盘输入enter就可以存,后面发现每张图片都一样,仔细分析后和订阅器发布器对消息的处理机制有关系,要实现订阅的为实时的消息,publisher和subscriber的队列大小应该都为1。

2.数据标注和增广

​ 在windows上面进行,标注使用labelImg,增广使用的是Github上面的项目(需要修改,不然会出现xmin>xmaxh或者ymin>ymx的问题)

标注比较简单,香蕉、芬达、可乐和雪碧标签分别为banan,fenda, cola, spirit

具体过程不在这里叙述,最后得到的应该是与那100张图片相对应的xml文件

具体介绍数据的增广:

将原始数据集图片进行剪裁、平移、改变亮度、加噪声、旋转、镜像等变换扩充数据集,同时将其对应的xml标签进行转换

第一步:新建DataAugmentforLabelImg.py

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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
# -*- coding=utf-8 -*-
##############################################################
# description:
# data augmentation for obeject detection
# author:
# pureyang 2019-08-26
# 参考:https://github.com/maozezhong/CV_ToolBox/blob/master/DataAugForObjectDetection

##############################################################

# 包括:
# 1. 裁剪(需改变bbox)
# 2. 平移(需改变bbox)
# 3. 改变亮度
# 4. 加噪声
# 5. 旋转角度(需要改变bbox)
# 6. 镜像(需要改变bbox)
# 7. cutout
# 注意:
# random.seed(),相同的seed,产生的随机数是一样的!!


import time
import random
import copy
import cv2
import os
import math
import numpy as np
from skimage.util import random_noise
from lxml import etree, objectify
import xml.etree.ElementTree as ETl
import argparse


# 显示图片
def show_pic(img, bboxes=None):
'''
输入:
img:图像array
bboxes:图像的所有boudning box list, 格式为[[x_min, y_min, x_max, y_max]....]
names:每个box对应的名称
'''
for i in range(len(bboxes)):
bbox = bboxes[i]
x_min = bbox[0]
y_min = bbox[1]
x_max = bbox[2]
y_max = bbox[3]
cv2.rectangle(img, (int(x_min), int(y_min)), (int(x_max), int(y_max)), (0, 255, 0), 3)
cv2.namedWindow('pic', 0) # 1表示原图
cv2.moveWindow('pic', 0, 0)
cv2.resizeWindow('pic', 1200, 800) # 可视化的图片大小
cv2.imshow('pic', img)
cv2.waitKey(0)
cv2.destroyAllWindows()


# 图像均为cv2读取
class DataAugmentForObjectDetection():
def __init__(self, rotation_rate=0.5, max_rotation_angle=5,
crop_rate=0.5, shift_rate=0.5, change_light_rate=0.5,
add_noise_rate=0.5, flip_rate=0.5,
cutout_rate=0.5, cut_out_length=50, cut_out_holes=1, cut_out_threshold=0.5,
is_addNoise=True, is_changeLight=True, is_cutout=True, is_rotate_img_bbox=True,
is_crop_img_bboxes=True, is_shift_pic_bboxes=True, is_filp_pic_bboxes=True):

# 配置各个操作的属性
self.rotation_rate = rotation_rate
self.max_rotation_angle = max_rotation_angle
self.crop_rate = crop_rate
self.shift_rate = shift_rate
self.change_light_rate = change_light_rate
self.add_noise_rate = add_noise_rate
self.flip_rate = flip_rate
self.cutout_rate = cutout_rate

self.cut_out_length = cut_out_length
self.cut_out_holes = cut_out_holes
self.cut_out_threshold = cut_out_threshold

# 是否使用某种增强方式
self.is_addNoise = is_addNoise
self.is_changeLight = is_changeLight
self.is_cutout = is_cutout
self.is_rotate_img_bbox = is_rotate_img_bbox
self.is_crop_img_bboxes = is_crop_img_bboxes
self.is_shift_pic_bboxes = is_shift_pic_bboxes
self.is_filp_pic_bboxes = is_filp_pic_bboxes

# 加噪声
def _addNoise(self, img):
'''
输入:
img:图像array
输出:
加噪声后的图像array,由于输出的像素是在[0,1]之间,所以得乘以255
'''
# return cv2.GaussianBlur(img, (11, 11), 0)
return random_noise(img, mode='gaussian', seed=int(time.time()), clip=True) * 255

# 调整亮度
def _changeLight(self, img):
alpha = random.uniform(0.35, 1)
blank = np.zeros(img.shape, img.dtype)
return cv2.addWeighted(img, alpha, blank, 1 - alpha, 0)

# cutout
def _cutout(self, img, bboxes, length=100, n_holes=1, threshold=0.5):
'''
原版本:https://github.com/uoguelph-mlrg/Cutout/blob/master/util/cutout.py
Randomly mask out one or more patches from an image.
Args:
img : a 3D numpy array,(h,w,c)
bboxes : 框的坐标
n_holes (int): Number of patches to cut out of each image.
length (int): The length (in pixels) of each square patch.
'''

def cal_iou(boxA, boxB):
'''
boxA, boxB为两个框,返回iou
boxB为bouding box
'''
# determine the (x, y)-coordinates of the intersection rectangle
xA = max(boxA[0], boxB[0])
yA = max(boxA[1], boxB[1])
xB = min(boxA[2], boxB[2])
yB = min(boxA[3], boxB[3])

if xB <= xA or yB <= yA:
return 0.0

# compute the area of intersection rectangle
interArea = (xB - xA + 1) * (yB - yA + 1)

# compute the area of both the prediction and ground-truth
# rectangles
boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)
boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)
iou = interArea / float(boxBArea)
return iou

# 得到h和w
if img.ndim == 3:
h, w, c = img.shape
else:
_, h, w, c = img.shape
mask = np.ones((h, w, c), np.float32)
for n in range(n_holes):
chongdie = True # 看切割的区域是否与box重叠太多
while chongdie:
y = np.random.randint(h)
x = np.random.randint(w)

y1 = np.clip(y - length // 2, 0,
h) # numpy.clip(a, a_min, a_max, out=None), clip这个函数将将数组中的元素限制在a_min, a_max之间,大于a_max的就使得它等于 a_max,小于a_min,的就使得它等于a_min
y2 = np.clip(y + length // 2, 0, h)
x1 = np.clip(x - length // 2, 0, w)
x2 = np.clip(x + length // 2, 0, w)

chongdie = False
for box in bboxes:
if cal_iou([x1, y1, x2, y2], box) > threshold:
chongdie = True
break
mask[y1: y2, x1: x2, :] = 0.
img = img * mask
return img

# 旋转
def _rotate_img_bbox(self, img, bboxes, angle=5, scale=1.):
'''
参考:https://blog.csdn.net/u014540717/article/details/53301195crop_rate
输入:
img:图像array,(h,w,c)
bboxes:该图像包含的所有boundingboxs,一个list,每个元素为[x_min, y_min, x_max, y_max],要确保是数值
angle:旋转角度
scale:默认1
输出:
rot_img:旋转后的图像array
rot_bboxes:旋转后的boundingbox坐标list
'''
# ---------------------- 旋转图像 ----------------------
w = img.shape[1]
h = img.shape[0]
# 角度变弧度
rangle = np.deg2rad(angle) # angle in radians
# now calculate new image width and height
nw = (abs(np.sin(rangle) * h) + abs(np.cos(rangle) * w)) * scale
nh = (abs(np.cos(rangle) * h) + abs(np.sin(rangle) * w)) * scale
# ask OpenCV for the rotation matrix
rot_mat = cv2.getRotationMatrix2D((nw * 0.5, nh * 0.5), angle, scale)
# calculate the move from the old center to the new center combined
# with the rotation
rot_move = np.dot(rot_mat, np.array([(nw - w) * 0.5, (nh - h) * 0.5, 0]))
# the move only affects the translation, so update the translation
rot_mat[0, 2] += rot_move[0]
rot_mat[1, 2] += rot_move[1]
# 仿射变换
rot_img = cv2.warpAffine(img, rot_mat, (int(math.ceil(nw)), int(math.ceil(nh))), flags=cv2.INTER_LANCZOS4)

# ---------------------- 矫正bbox坐标 ----------------------
# rot_mat是最终的旋转矩阵
# 获取原始bbox的四个中点,然后将这四个点转换到旋转后的坐标系下
rot_bboxes = list()
for bbox in bboxes:
xmin = bbox[0]
ymin = bbox[1]
xmax = bbox[2]
ymax = bbox[3]
point1 = np.dot(rot_mat, np.array([(xmin + xmax) / 2, ymin, 1]))
point2 = np.dot(rot_mat, np.array([xmax, (ymin + ymax) / 2, 1]))
point3 = np.dot(rot_mat, np.array([(xmin + xmax) / 2, ymax, 1]))
point4 = np.dot(rot_mat, np.array([xmin, (ymin + ymax) / 2, 1]))
# 合并np.array
concat = np.vstack((point1, point2, point3, point4))
# 改变array类型
concat = concat.astype(np.int32)
# 得到旋转后的坐标
rx, ry, rw, rh = cv2.boundingRect(concat)
rx_min = rx
ry_min = ry
rx_max = rx + rw
ry_max = ry + rh
# 加入list中
rot_bboxes.append([rx_min, ry_min, rx_max, ry_max])

return rot_img, rot_bboxes

# 裁剪
def _crop_img_bboxes(self, img, bboxes):
'''
裁剪后的图片要包含所有的框
输入:
img:图像array
bboxes:该图像包含的所有boundingboxs,一个list,每个元素为[x_min, y_min, x_max, y_max],要确保是数值
输出:
crop_img:裁剪后的图像array
crop_bboxes:裁剪后的bounding box的坐标list
'''
# ---------------------- 裁剪图像 ----------------------
w = img.shape[1]
h = img.shape[0]
x_min = w # 裁剪后的包含所有目标框的最小的框
x_max = 0
y_min = h
y_max = 0
for bbox in bboxes:
x_min = min(x_min, bbox[0])
y_min = min(y_min, bbox[1])
x_max = max(x_max, bbox[2])
y_max = max(y_max, bbox[3])

d_to_left = x_min # 包含所有目标框的最小框到左边的距离
d_to_right = w - x_max # 包含所有目标框的最小框到右边的距离
d_to_top = y_min # 包含所有目标框的最小框到顶端的距离
d_to_bottom = h - y_max # 包含所有目标框的最小框到底部的距离

# 随机扩展这个最小框
crop_x_min = int(x_min - random.uniform(0, d_to_left))
crop_y_min = int(y_min - random.uniform(0, d_to_top))
crop_x_max = int(x_max + random.uniform(0, d_to_right))
crop_y_max = int(y_max + random.uniform(0, d_to_bottom))

# 随机扩展这个最小框 , 防止别裁的太小
# crop_x_min = int(x_min - random.uniform(d_to_left//2, d_to_left))
# crop_y_min = int(y_min - random.uniform(d_to_top//2, d_to_top))
# crop_x_max = int(x_max + random.uniform(d_to_right//2, d_to_right))
# crop_y_max = int(y_max + random.uniform(d_to_bottom//2, d_to_bottom))

# 确保不要越界
crop_x_min = max(0, crop_x_min)
crop_y_min = max(0, crop_y_min)
crop_x_max = min(w, crop_x_max)
crop_y_max = min(h, crop_y_max)

crop_img = img[crop_y_min:crop_y_max, crop_x_min:crop_x_max]

# ---------------------- 裁剪boundingbox ----------------------
# 裁剪后的boundingbox坐标计算
crop_bboxes = list()
for bbox in bboxes:
crop_bboxes.append([bbox[0] - crop_x_min, bbox[1] - crop_y_min, bbox[2] - crop_x_min, bbox[3] - crop_y_min])

return crop_img, crop_bboxes

# 平移
def _shift_pic_bboxes(self, img, bboxes):
'''
参考:https://blog.csdn.net/sty945/article/details/79387054
平移后的图片要包含所有的框
输入:
img:图像array
bboxes:该图像包含的所有boundingboxs,一个list,每个元素为[x_min, y_min, x_max, y_max],要确保是数值
输出:
shift_img:平移后的图像array
shift_bboxes:平移后的bounding box的坐标list
'''
# ---------------------- 平移图像 ----------------------
w = img.shape[1]
h = img.shape[0]
x_min = w # 裁剪后的包含所有目标框的最小的框
x_max = 0
y_min = h
y_max = 0
for bbox in bboxes:
x_min = min(x_min, bbox[0])
y_min = min(y_min, bbox[1])
x_max = max(x_max, bbox[2])
y_max = max(y_max, bbox[3])

d_to_left = x_min # 包含所有目标框的最大左移动距离
d_to_right = w - x_max # 包含所有目标框的最大右移动距离
d_to_top = y_min # 包含所有目标框的最大上移动距离
d_to_bottom = h - y_max # 包含所有目标框的最大下移动距离

x = random.uniform(-(d_to_left - 1) / 3, (d_to_right - 1) / 3)
y = random.uniform(-(d_to_top - 1) / 3, (d_to_bottom - 1) / 3)

M = np.float32([[1, 0, x], [0, 1, y]]) # x为向左或右移动的像素值,正为向右负为向左; y为向上或者向下移动的像素值,正为向下负为向上
shift_img = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))

# ---------------------- 平移boundingbox ----------------------
shift_bboxes = list()
for bbox in bboxes:
shift_bboxes.append([bbox[0] + x, bbox[1] + y, bbox[2] + x, bbox[3] + y])

return shift_img, shift_bboxes

# 镜像
def _filp_pic_bboxes(self, img, bboxes):
'''
参考:https://blog.csdn.net/jningwei/article/details/78753607
平移后的图片要包含所有的框
输入:
img:图像array
bboxes:该图像包含的所有boundingboxs,一个list,每个元素为[x_min, y_min, x_max, y_max],要确保是数值
输出:
flip_img:平移后的图像array
flip_bboxes:平移后的bounding box的坐标list
'''
# ---------------------- 翻转图像 ----------------------

flip_img = copy.deepcopy(img)
h, w, _ = img.shape

sed = random.random()

if 0 < sed < 0.33: # 0.33的概率水平翻转,0.33的概率垂直翻转,0.33是对角反转
flip_img = cv2.flip(flip_img, 0) # _flip_x
inver = 0
elif 0.33 < sed < 0.66:
flip_img = cv2.flip(flip_img, 1) # _flip_y
inver = 1
else:
flip_img = cv2.flip(flip_img, -1) # flip_x_y
inver = -1

# ---------------------- 调整boundingbox ----------------------
flip_bboxes = list()
for box in bboxes:
x_min = box[0]
y_min = box[1]
x_max = box[2]
y_max = box[3]
if inver == 0:
flip_bboxes.append([x_max, h - y_min, x_min, h - y_max])
elif inver == 1:
flip_bboxes.append([w - x_max, y_min, w - x_min, y_max])
elif inver == -1:
flip_bboxes.append([w - x_min, h - y_max, w - x_max, h - y_min])

return flip_img, flip_bboxes

# 图像增强方法
def dataAugment(self, img, bboxes):
'''
图像增强
输入:
img:图像array
bboxes:该图像的所有框坐标
输出:
img:增强后的图像
bboxes:增强后图片对应的box
'''
change_num = 0 # 改变的次数
# print('------')
while change_num < 1: # 默认至少有一种数据增强生效

if self.is_rotate_img_bbox:
if random.random() > self.rotation_rate: # 旋转
change_num += 1
angle = random.uniform(-self.max_rotation_angle, self.max_rotation_angle)
scale = random.uniform(0.7, 0.8)
img, bboxes = self._rotate_img_bbox(img, bboxes, angle, scale)

if self.is_shift_pic_bboxes:
if random.random() < self.shift_rate: # 平移
change_num += 1
img, bboxes = self._shift_pic_bboxes(img, bboxes)

if self.is_changeLight:
if random.random() > self.change_light_rate: # 改变亮度
change_num += 1
img = self._changeLight(img)

if self.is_addNoise:
if random.random() < self.add_noise_rate: # 加噪声
change_num += 1
img = self._addNoise(img)
if self.is_cutout:
if random.random() < self.cutout_rate: # cutout
change_num += 1
img = self._cutout(img, bboxes, length=self.cut_out_length, n_holes=self.cut_out_holes,
threshold=self.cut_out_threshold)
if self.is_filp_pic_bboxes:
if random.random() < self.flip_rate: # 翻转
change_num += 1
img, bboxes = self._filp_pic_bboxes(img, bboxes)

return img, bboxes


# xml解析工具
class ToolHelper():
# 从xml文件中提取bounding box信息, 格式为[[x_min, y_min, x_max, y_max, name]]
def parse_xml(self, path):
'''
输入:
xml_path: xml的文件路径
输出:
从xml文件中提取bounding box信息, 格式为[[x_min, y_min, x_max, y_max, name]]
'''
tree = ETl.parse(path)
root = tree.getroot()
objs = root.findall('object')
coords = list()
for ix, obj in enumerate(objs):
name = obj.find('name').text
box = obj.find('bndbox')
x_min = int(box[0].text)
y_min = int(box[1].text)
x_max = int(box[2].text)
y_max = int(box[3].text)
coords.append([x_min, y_min, x_max, y_max, name])
return coords

# 保存图片结果
def save_img(self, file_name, save_folder, img):
cv2.imwrite(os.path.join(save_folder, file_name), img)

# 保持xml结果
def save_xml(self, file_name, save_folder, img_info, height, width, channel, bboxs_info,image_name,image_folder,image):
'''
:param file_name:文件名
:param save_folder:#保存的xml文件的结果
:param height:图片的信息
:param width:图片的宽度
:param channel:通道
:return:
'''
folder_name, img_name = img_info # 得到图片的信息

E = objectify.ElementMaker(annotate=False)

anno_tree = E.annotation(
E.folder(folder_name),
E.filename(img_name),
E.path(os.path.join(folder_name, img_name)),
E.source(
E.database('Unknown'),
),
E.size(
E.width(width),
E.height(height),
E.depth(channel)
),
E.segmented(0),
)

labels, bboxs = bboxs_info # 得到边框和标签信息
for label, box in zip(labels, bboxs):
if box[0] > box[2]:
box[0], box[2] = box[2], box[0]
if box[1] > box[3]:
box[1], box[3] = box[3], box[1]
cv2.rectangle(image, (box[0],box[1]), (box[2], box[3]), (0, 255, 0), 4)
cv2.imwrite(os.path.join(image_folder, image_name), image)
anno_tree.append(
E.object(
E.name(label),
E.pose('Unspecified'),
E.truncated('0'),
E.difficult('0'),
E.bndbox(
E.xmin(box[0]),
E.ymin(box[1]),
E.xmax(box[2]),
E.ymax(box[3])
)
))

etree.ElementTree(anno_tree).write(os.path.join(save_folder, file_name), pretty_print=True)


if __name__ == '__main__':

need_aug_num = 30 # 每张图片需要增强的次数

is_endwidth_dot = True # 文件是否以.jpg或者png结尾

dataAug = DataAugmentForObjectDetection() # 数据增强工具类

toolhelper = ToolHelper() # 工具
# 获取相关参数
parser = argparse.ArgumentParser()
parser.add_argument('--source_img_path', type=str, default='data/Images')
parser.add_argument('--source_xml_path', type=str, default='data/Annotations')
parser.add_argument('--save_img_path', type=str, default='data/Images2')
parser.add_argument('--save_img_path2', type=str, default='data/Images3')
parser.add_argument('--save_xml_path', type=str, default='data/Annotations2')
args = parser.parse_args()
source_img_path = args.source_img_path # 图片原始位置

source_xml_path = args.source_xml_path # xml的原始位置

save_img_path = args.save_img_path # 图片增强结果保存文件
save_img_path2 = args.save_img_path2 # 图片增强结果验证文件
save_xml_path = args.save_xml_path # xml增强结果保存文件

# 如果保存文件夹不存在就创建
if not os.path.exists(save_img_path):
os.mkdir(save_img_path)

if not os.path.exists(save_xml_path):
os.mkdir(save_xml_path)

for parent, _, files in os.walk(source_img_path):
files.sort()
for file in files:
cnt = 0
pic_path = os.path.join(parent, file)
xml_path = os.path.join(source_xml_path, file[:-4] + '.xml')
values = toolhelper.parse_xml(xml_path) # 解析得到box信息,格式为[[x_min,y_min,x_max,y_max,name]]
coords = [v[:4] for v in values] # 得到框
labels = [v[-1] for v in values] # 对象的标签

# 如果图片是有后缀的
if is_endwidth_dot:
# 找到文件的最后名字
dot_index = file.rfind('.')
_file_prefix = file[:dot_index] # 文件名的前缀
_file_suffix = file[dot_index:] # 文件名的后缀
img = cv2.imread(pic_path)

# show_pic(img, coords) # 显示原图
while cnt < need_aug_num: # 继续增强
auged_img, auged_bboxes = dataAug.dataAugment(img, coords)

auged_bboxes_int = np.array(auged_bboxes).astype(np.int32)
height, width, channel = auged_img.shape # 得到图片的属性
img_name = '{}_{}{}'.format(_file_prefix, cnt + 1, _file_suffix) # 图片保存的信息
toolhelper.save_img(img_name, save_img_path,
auged_img) # 保存增强图片

toolhelper.save_xml('{}_{}.xml'.format(_file_prefix, cnt + 1),
save_xml_path, (save_img_path, img_name), height, width, channel,
(labels, auged_bboxes_int),img_name,save_img_path2,auged_img) # 保存xml文件
# show_pic(auged_img, auged_bboxes) # 强化后的图
print(img_name)
cnt += 1 # 继续增强下一张

注意 need_aug_num = 30 # 每张图片需要增强的次数,这里将得到3000张变换后的图片

代码中有五处路径,分别为

data/Images:100张图片

data/Images2:3000张变换后的图片

data/Images3:变换后的标注(用于检验数据增广是否正确)

data/Annotations:100张图片对应的xml标签

data/Annotations2:3000张变换后的图片对应的xml标签

注意data和DataAugmentforLabelImg.py在同一个目录!!!

增广后的图片:

增广后的xml标签:

对增广是否正确的验证:

可以看出每个画框都很准确!!!!

第二步:新建transform.py用于将标签转换为txt标签
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
import os
import xml.etree.ElementTree as ET

classes = ["banana", "fenda", "cola", "spirit"]


# 将x1, y1, x2, y2转换成yolov5所需要的x, y, w, h格式
def xyxy2xywh(size, box):
dw = 1. / size[0]
dh = 1. / size[1]
x = (box[0] + box[2]) / 2 * dw
y = (box[1] + box[3]) / 2 * dh
w = (box[2] - box[0]) * dw
h = (box[3] - box[1]) * dh
return (x, y, w, h) # 返回的都是标准化后的值


def voc2yolo(path):
# 可以打印看看该路径是否正确
print(len(os.listdir(path)))
# 遍历每一个xml文件
for file in os.listdir(path):
# xml文件的完整路径, 注意:因为是路径所以要确保准确,我是直接使用了字符串拼接, 为了保险可以用os.path.join(path, file)
label_file = path + file
print(label_file)
# 最终要改成的txt格式文件,这里我是放在voc2007/labels/下面
# 注意: labels文件夹必须存在,没有就先创建,不然会报错
out_file = open(path.replace('Annotations2', 'labels2') + file.replace('xml', 'txt'), 'w')


# 开始解析xml文件
tree = ET.parse(label_file)
root = tree.getroot()
size = root.find('size') # 图片的shape值
w = int(size.find('width').text)
h = int(size.find('height').text)
for obj in root.iter('object'):
cls = obj.find('name').text
# print(cls)
if cls not in classes:
continue
cls_id = classes.index(cls)
# 获取整个bounding box框
bndbox = obj.find('bndbox')
# xml给出的是x1, y1, x2, y2
box = [float(bndbox.find('xmin').text), float(bndbox.find('ymin').text), float(bndbox.find('xmax').text),
float(bndbox.find('ymax').text)]
# 将x1, y1, x2, y2转换成yolov5所需要的x_center, y_center, w, h格式
bbox = xyxy2xywh((w, h), box)
# 写入目标文件中,格式为 id x y w h

out_file.write(str(cls_id) + " " + " ".join(str(x) for x in bbox) + '\n')


if __name__ == '__main__':
# 这里要改成自己数据集路径的格式
path = 'Annotations2/'
voc2yolo(path)

这里需要十分注意的是:classes = [“banana”, “fenda”, “cola”, “spirit”] 分别对应序号0,1,2,3!!!!

要在.py文件同目录下新建Annotations2文件夹和labels2文件夹,把之前增广后的xml标签文件全部放进Annotations2文件夹中,运行后labels2下即有3000个txt格式的标签

到这里所需数据集已经准备好,下一步就是用于训练啦!!!

这里也提供我的数据集的下载,百度网盘链接:https://pan.baidu.com/s/1mYqwDH46OD3p9Jrfbvj6xQ(提取码1234)大小一个多G

训练前的准备

darknet训练前还是有很多地方需要配置和修改的,下面是是最简洁快速的配置方法了

1
2
cd ~/yolo_detect/src/darknet_ros/darknet
make

编译好后在darknet下新建文件夹classify

第一步:模仿以下的文件结构创建文件

文件夹中的文件形式如下所示:

其中:

backup存放了权重文件
dataset里面存放了image和txt格式的标签
classify.data指定了训练用到的数据集和权重的路径
classify.names指定了类别名称,顺序应与label中的对应
detapre.sh用于生成text.txt,train.txt这两个文本
test.txt,train.txt中分别存放了数据集和验证集每张图片和标签的绝对路径

必须准备好这些文件后再进行下一步!!!!!!!

第二步:修改yolov3-tiny网络的配置

需要修改的地方:

需要修改的地方为cfg下的yolov3-tiny.cfg
将#Testing注释,将#Traning取消注释

同时有两个yolo层及与它们相邻的convolutional层需要修改
classes的值改为4(香蕉,可乐,雪碧,芬达)
filters的值为3*(classes+5)=27

第三步:修改保存权重的频率

其次在examples下的detector.c中可以将138行改为if(i%1000==0 || (i < 1000 && i%100 == 0)){即1000代以前没一百代保存一次权重,1000代以后每隔1000代保存一次

第四步:开始训练

sudo ./darknet detector train classify/classify.data cfg/yolov3-tiny.cfg

出现报错:

1
./darknet: error while loading shared libraries: libcudart.so.9.2: cannot open shared object file: No such file or directory

解决办法:

1
2
3
4
sudo cp /usr/local/cuda-9.2/lib64/libcudart.so.9.2 /usr/local/lib/libcudart.so.9.2 && sudo ldconfig 
sudo cp /usr/local/cuda-9.2/lib64/libcublas.so.9.2 /usr/local/lib/libcublas.so.9.2 && sudo ldconfig
sudo cp /usr/local/cuda-9.2/lib64/libcurand.so.9.2 /usr/local/lib/libcurand.so.9.2 && sudo ldconfig
sudo cp /usr/local/cuda-9.2/lib64/libcudnn.so.7 /usr/local/lib/libcudnn.so.7 && sudo ldconfig

重新执行:

sudo ./darknet detector train classify/classify.data cfg/yolov3-tiny.cfg

成功开始训练:

大概训练了一个小时训练到5000代,得到权重文件yolov3-tiny_5000.weights

检验训练结果

第一步:

进入darknet ros
将所的权重文件放入yolo_network_config/weights下
由于darknet并没有yolov3-tiny的配置文件
所以需要在config下新建yolov3-tiny.yaml,内容如图所示

第二步:

复制刚刚改过的yolov3-tiny.cfg到yolo_network_config/cfg下

第三步:

将launch下的darknet_ros.launch
内容修改为如图所示

第四步:

打开config下的yaml

修改相机话题为 topic: /camera/color/image_raw

从中可以看到该节点运行时会发布三个话题
/darknet_ros/found_object
/darknet_ros/bounding_boxes
/darknet_ros/detection_image

/darknet_ros/bounding_boxes的消息示例如图所示

第五步:

上述步骤都完成后

通过gazebo加载仿真环境
运行roslaunch darknet_ros darknet_ros.launch
可以发现检测效果很好且处理速度快,检测结果见视频

分类之后的抓取姿态检测

ORK或者几何方法???敬请期待