You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

dataset.py 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """YOLOv3 dataset"""
  16. from __future__ import division
  17. import os
  18. import numpy as np
  19. from PIL import Image
  20. from matplotlib.colors import rgb_to_hsv, hsv_to_rgb
  21. import mindspore.dataset as de
  22. from mindspore.mindrecord import FileWriter
  23. import mindspore.dataset.transforms.vision.c_transforms as C
  24. from config import ConfigYOLOV3ResNet18
  25. iter_cnt = 0
  26. _NUM_BOXES = 50
  27. def preprocess_fn(image, box, is_training):
  28. """Preprocess function for dataset."""
  29. config_anchors = [10, 13, 16, 30, 33, 23, 30, 61, 62, 45, 59, 119, 116, 90, 156, 198, 163, 326]
  30. anchors = np.array([float(x) for x in config_anchors]).reshape(-1, 2)
  31. do_hsv = False
  32. max_boxes = 20
  33. num_classes = ConfigYOLOV3ResNet18.num_classes
  34. def _rand(a=0., b=1.):
  35. return np.random.rand() * (b - a) + a
  36. def _preprocess_true_boxes(true_boxes, anchors, in_shape=None):
  37. """Get true boxes."""
  38. num_layers = anchors.shape[0] // 3
  39. anchor_mask = [[6, 7, 8], [3, 4, 5], [0, 1, 2]]
  40. true_boxes = np.array(true_boxes, dtype='float32')
  41. # input_shape = np.array([in_shape, in_shape], dtype='int32')
  42. input_shape = np.array(in_shape, dtype='int32')
  43. boxes_xy = (true_boxes[..., 0:2] + true_boxes[..., 2:4]) // 2.
  44. boxes_wh = true_boxes[..., 2:4] - true_boxes[..., 0:2]
  45. true_boxes[..., 0:2] = boxes_xy / input_shape[::-1]
  46. true_boxes[..., 2:4] = boxes_wh / input_shape[::-1]
  47. grid_shapes = [input_shape // 32, input_shape // 16, input_shape // 8]
  48. y_true = [np.zeros((grid_shapes[l][0], grid_shapes[l][1], len(anchor_mask[l]),
  49. 5 + num_classes), dtype='float32') for l in range(num_layers)]
  50. anchors = np.expand_dims(anchors, 0)
  51. anchors_max = anchors / 2.
  52. anchors_min = -anchors_max
  53. valid_mask = boxes_wh[..., 0] >= 1
  54. wh = boxes_wh[valid_mask]
  55. if len(wh) >= 1:
  56. wh = np.expand_dims(wh, -2)
  57. boxes_max = wh / 2.
  58. boxes_min = -boxes_max
  59. intersect_min = np.maximum(boxes_min, anchors_min)
  60. intersect_max = np.minimum(boxes_max, anchors_max)
  61. intersect_wh = np.maximum(intersect_max - intersect_min, 0.)
  62. intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1]
  63. box_area = wh[..., 0] * wh[..., 1]
  64. anchor_area = anchors[..., 0] * anchors[..., 1]
  65. iou = intersect_area / (box_area + anchor_area - intersect_area)
  66. best_anchor = np.argmax(iou, axis=-1)
  67. for t, n in enumerate(best_anchor):
  68. for l in range(num_layers):
  69. if n in anchor_mask[l]:
  70. i = np.floor(true_boxes[t, 0] * grid_shapes[l][1]).astype('int32')
  71. j = np.floor(true_boxes[t, 1] * grid_shapes[l][0]).astype('int32')
  72. k = anchor_mask[l].index(n)
  73. c = true_boxes[t, 4].astype('int32')
  74. y_true[l][j, i, k, 0:4] = true_boxes[t, 0:4]
  75. y_true[l][j, i, k, 4] = 1.
  76. y_true[l][j, i, k, 5 + c] = 1.
  77. pad_gt_box0 = np.zeros(shape=[50, 4], dtype=np.float32)
  78. pad_gt_box1 = np.zeros(shape=[50, 4], dtype=np.float32)
  79. pad_gt_box2 = np.zeros(shape=[50, 4], dtype=np.float32)
  80. mask0 = np.reshape(y_true[0][..., 4:5], [-1])
  81. gt_box0 = np.reshape(y_true[0][..., 0:4], [-1, 4])
  82. gt_box0 = gt_box0[mask0 == 1]
  83. pad_gt_box0[:gt_box0.shape[0]] = gt_box0
  84. mask1 = np.reshape(y_true[1][..., 4:5], [-1])
  85. gt_box1 = np.reshape(y_true[1][..., 0:4], [-1, 4])
  86. gt_box1 = gt_box1[mask1 == 1]
  87. pad_gt_box1[:gt_box1.shape[0]] = gt_box1
  88. mask2 = np.reshape(y_true[2][..., 4:5], [-1])
  89. gt_box2 = np.reshape(y_true[2][..., 0:4], [-1, 4])
  90. gt_box2 = gt_box2[mask2 == 1]
  91. pad_gt_box2[:gt_box2.shape[0]] = gt_box2
  92. return y_true[0], y_true[1], y_true[2], pad_gt_box0, pad_gt_box1, pad_gt_box2
  93. def _infer_data(img_data, input_shape, box):
  94. w, h = img_data.size
  95. input_h, input_w = input_shape
  96. scale = min(float(input_w) / float(w), float(input_h) / float(h))
  97. nw = int(w * scale)
  98. nh = int(h * scale)
  99. img_data = img_data.resize((nw, nh), Image.BICUBIC)
  100. new_image = np.zeros((input_h, input_w, 3), np.float32)
  101. new_image.fill(128)
  102. img_data = np.array(img_data)
  103. if len(img_data.shape) == 2:
  104. img_data = np.expand_dims(img_data, axis=-1)
  105. img_data = np.concatenate([img_data, img_data, img_data], axis=-1)
  106. dh = int((input_h - nh) / 2)
  107. dw = int((input_w - nw) / 2)
  108. new_image[dh:(nh + dh), dw:(nw + dw), :] = img_data
  109. new_image /= 255.
  110. new_image = np.transpose(new_image, (2, 0, 1))
  111. new_image = np.expand_dims(new_image, 0)
  112. return new_image, np.array([h, w], np.float32), box
  113. def _data_aug(image, box, is_training, jitter=0.3, hue=0.1, sat=1.5, val=1.5, image_size=(352, 640)):
  114. """Data augmentation function."""
  115. if not isinstance(image, Image.Image):
  116. image = Image.fromarray(image)
  117. iw, ih = image.size
  118. ori_image_shape = np.array([ih, iw], np.int32)
  119. h, w = image_size
  120. if not is_training:
  121. return _infer_data(image, image_size, box)
  122. flip = _rand() < .5
  123. # correct boxes
  124. box_data = np.zeros((max_boxes, 5))
  125. while True:
  126. # Prevent the situation that all boxes are eliminated
  127. new_ar = float(w) / float(h) * _rand(1 - jitter, 1 + jitter) / \
  128. _rand(1 - jitter, 1 + jitter)
  129. scale = _rand(0.25, 2)
  130. if new_ar < 1:
  131. nh = int(scale * h)
  132. nw = int(nh * new_ar)
  133. else:
  134. nw = int(scale * w)
  135. nh = int(nw / new_ar)
  136. dx = int(_rand(0, w - nw))
  137. dy = int(_rand(0, h - nh))
  138. if len(box) >= 1:
  139. t_box = box.copy()
  140. np.random.shuffle(t_box)
  141. t_box[:, [0, 2]] = t_box[:, [0, 2]] * float(nw) / float(iw) + dx
  142. t_box[:, [1, 3]] = t_box[:, [1, 3]] * float(nh) / float(ih) + dy
  143. if flip:
  144. t_box[:, [0, 2]] = w - t_box[:, [2, 0]]
  145. t_box[:, 0:2][t_box[:, 0:2] < 0] = 0
  146. t_box[:, 2][t_box[:, 2] > w] = w
  147. t_box[:, 3][t_box[:, 3] > h] = h
  148. box_w = t_box[:, 2] - t_box[:, 0]
  149. box_h = t_box[:, 3] - t_box[:, 1]
  150. t_box = t_box[np.logical_and(box_w > 1, box_h > 1)] # discard invalid box
  151. if len(t_box) >= 1:
  152. box = t_box
  153. break
  154. box_data[:len(box)] = box
  155. # resize image
  156. image = image.resize((nw, nh), Image.BICUBIC)
  157. # place image
  158. new_image = Image.new('RGB', (w, h), (128, 128, 128))
  159. new_image.paste(image, (dx, dy))
  160. image = new_image
  161. # flip image or not
  162. if flip:
  163. image = image.transpose(Image.FLIP_LEFT_RIGHT)
  164. # convert image to gray or not
  165. gray = _rand() < .25
  166. if gray:
  167. image = image.convert('L').convert('RGB')
  168. # when the channels of image is 1
  169. image = np.array(image)
  170. if len(image.shape) == 2:
  171. image = np.expand_dims(image, axis=-1)
  172. image = np.concatenate([image, image, image], axis=-1)
  173. # distort image
  174. hue = _rand(-hue, hue)
  175. sat = _rand(1, sat) if _rand() < .5 else 1 / _rand(1, sat)
  176. val = _rand(1, val) if _rand() < .5 else 1 / _rand(1, val)
  177. image_data = image / 255.
  178. if do_hsv:
  179. x = rgb_to_hsv(image_data)
  180. x[..., 0] += hue
  181. x[..., 0][x[..., 0] > 1] -= 1
  182. x[..., 0][x[..., 0] < 0] += 1
  183. x[..., 1] *= sat
  184. x[..., 2] *= val
  185. x[x > 1] = 1
  186. x[x < 0] = 0
  187. image_data = hsv_to_rgb(x) # numpy array, 0 to 1
  188. image_data = image_data.astype(np.float32)
  189. # preprocess bounding boxes
  190. bbox_true_1, bbox_true_2, bbox_true_3, gt_box1, gt_box2, gt_box3 = \
  191. _preprocess_true_boxes(box_data, anchors, image_size)
  192. return image_data, bbox_true_1, bbox_true_2, bbox_true_3, \
  193. ori_image_shape, gt_box1, gt_box2, gt_box3
  194. if is_training:
  195. images, bbox_1, bbox_2, bbox_3, _, gt_box1, gt_box2, gt_box3 = _data_aug(image, box, is_training)
  196. return images, bbox_1, bbox_2, bbox_3, gt_box1, gt_box2, gt_box3
  197. images, shape, anno = _data_aug(image, box, is_training)
  198. return images, shape, anno
  199. def anno_parser(annos_str):
  200. """Parse annotation from string to list."""
  201. annos = []
  202. for anno_str in annos_str:
  203. anno = list(map(int, anno_str.strip().split(',')))
  204. annos.append(anno)
  205. return annos
  206. def filter_valid_data(image_dir, anno_path):
  207. """Filter valid image file, which both in image_dir and anno_path."""
  208. image_files = []
  209. image_anno_dict = {}
  210. if not os.path.isdir(image_dir):
  211. raise RuntimeError("Path given is not valid.")
  212. if not os.path.isfile(anno_path):
  213. raise RuntimeError("Annotation file is not valid.")
  214. with open(anno_path, "rb") as f:
  215. lines = f.readlines()
  216. for line in lines:
  217. line_str = line.decode("utf-8").strip()
  218. line_split = str(line_str).split(' ')
  219. file_name = line_split[0]
  220. if os.path.isfile(os.path.join(image_dir, file_name)):
  221. image_anno_dict[file_name] = anno_parser(line_split[1:])
  222. image_files.append(file_name)
  223. return image_files, image_anno_dict
  224. def data_to_mindrecord_byte_image(image_dir, anno_path, mindrecord_dir, prefix="yolo.mindrecord", file_num=8):
  225. """Create MindRecord file by image_dir and anno_path."""
  226. mindrecord_path = os.path.join(mindrecord_dir, prefix)
  227. writer = FileWriter(mindrecord_path, file_num)
  228. image_files, image_anno_dict = filter_valid_data(image_dir, anno_path)
  229. yolo_json = {
  230. "image": {"type": "bytes"},
  231. "annotation": {"type": "int64", "shape": [-1, 5]},
  232. }
  233. writer.add_schema(yolo_json, "yolo_json")
  234. for image_name in image_files:
  235. image_path = os.path.join(image_dir, image_name)
  236. with open(image_path, 'rb') as f:
  237. img = f.read()
  238. annos = np.array(image_anno_dict[image_name])
  239. row = {"image": img, "annotation": annos}
  240. writer.write_raw_data([row])
  241. writer.commit()
  242. def create_yolo_dataset(mindrecord_dir, batch_size=32, repeat_num=10, device_num=1, rank=0,
  243. is_training=True, num_parallel_workers=8):
  244. """Creatr YOLOv3 dataset with MindDataset."""
  245. ds = de.MindDataset(mindrecord_dir, columns_list=["image", "annotation"], num_shards=device_num, shard_id=rank,
  246. num_parallel_workers=num_parallel_workers, shuffle=is_training)
  247. decode = C.Decode()
  248. ds = ds.map(input_columns=["image"], operations=decode)
  249. compose_map_func = (lambda image, annotation: preprocess_fn(image, annotation, is_training))
  250. if is_training:
  251. hwc_to_chw = C.HWC2CHW()
  252. ds = ds.map(input_columns=["image", "annotation"],
  253. output_columns=["image", "bbox_1", "bbox_2", "bbox_3", "gt_box1", "gt_box2", "gt_box3"],
  254. columns_order=["image", "bbox_1", "bbox_2", "bbox_3", "gt_box1", "gt_box2", "gt_box3"],
  255. operations=compose_map_func, num_parallel_workers=num_parallel_workers)
  256. ds = ds.map(input_columns=["image"], operations=hwc_to_chw, num_parallel_workers=num_parallel_workers)
  257. ds = ds.batch(batch_size, drop_remainder=True)
  258. ds = ds.repeat(repeat_num)
  259. else:
  260. ds = ds.map(input_columns=["image", "annotation"],
  261. output_columns=["image", "image_shape", "annotation"],
  262. columns_order=["image", "image_shape", "annotation"],
  263. operations=compose_map_func, num_parallel_workers=num_parallel_workers)
  264. return ds