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 14 kB

5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. """SSD dataset"""
  16. from __future__ import division
  17. import os
  18. import math
  19. import itertools as it
  20. import numpy as np
  21. import cv2
  22. import mindspore.dataset as de
  23. import mindspore.dataset.transforms.vision.c_transforms as C
  24. from mindspore.mindrecord import FileWriter
  25. from config import ConfigSSD
  26. config = ConfigSSD()
  27. class GeneratDefaultBoxes():
  28. """
  29. Generate Default boxes for SSD, follows the order of (W, H, archor_sizes).
  30. `self.default_boxes` has a shape of [archor_sizes, H, W, 4], the last dimension is [x, y, w, h].
  31. `self.default_boxes_ltrb` has a shape as `self.default_boxes`, the last dimension is [x1, y1, x2, y2].
  32. """
  33. def __init__(self):
  34. fk = config.IMG_SHAPE[0] / np.array(config.STEPS)
  35. self.default_boxes = []
  36. for idex, feature_size in enumerate(config.FEATURE_SIZE):
  37. sk1 = config.SCALES[idex] / config.IMG_SHAPE[0]
  38. sk2 = config.SCALES[idex + 1] / config.IMG_SHAPE[0]
  39. sk3 = math.sqrt(sk1 * sk2)
  40. if config.NUM_DEFAULT[idex] == 3:
  41. all_sizes = [(0.5, 1.0), (1.0, 1.0), (1.0, 0.5)]
  42. else:
  43. all_sizes = [(sk1, sk1), (sk3, sk3)]
  44. for aspect_ratio in config.ASPECT_RATIOS[idex]:
  45. w, h = sk1 * math.sqrt(aspect_ratio), sk1 / math.sqrt(aspect_ratio)
  46. all_sizes.append((w, h))
  47. all_sizes.append((h, w))
  48. assert len(all_sizes) == config.NUM_DEFAULT[idex]
  49. for i, j in it.product(range(feature_size), repeat=2):
  50. for w, h in all_sizes:
  51. cx, cy = (j + 0.5) / fk[idex], (i + 0.5) / fk[idex]
  52. box = [np.clip(k, 0, 1) for k in (cx, cy, w, h)]
  53. self.default_boxes.append(box)
  54. def to_ltrb(cx, cy, w, h):
  55. return cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2
  56. # For IoU calculation
  57. self.default_boxes_ltrb = np.array(tuple(to_ltrb(*i) for i in self.default_boxes), dtype='float32')
  58. self.default_boxes = np.array(self.default_boxes, dtype='float32')
  59. default_boxes_ltrb = GeneratDefaultBoxes().default_boxes_ltrb
  60. default_boxes = GeneratDefaultBoxes().default_boxes
  61. x1, y1, x2, y2 = np.split(default_boxes_ltrb[:, :4], 4, axis=-1)
  62. vol_anchors = (x2 - x1) * (y2 - y1)
  63. matching_threshold = config.MATCH_THRESHOLD
  64. def ssd_bboxes_encode(boxes):
  65. """
  66. Labels anchors with ground truth inputs.
  67. Args:
  68. boxex: ground truth with shape [N, 5], for each row, it stores [x, y, w, h, cls].
  69. Returns:
  70. gt_loc: location ground truth with shape [num_anchors, 4].
  71. gt_label: class ground truth with shape [num_anchors, 1].
  72. num_matched_boxes: number of positives in an image.
  73. """
  74. def jaccard_with_anchors(bbox):
  75. """Compute jaccard score a box and the anchors."""
  76. # Intersection bbox and volume.
  77. xmin = np.maximum(x1, bbox[0])
  78. ymin = np.maximum(y1, bbox[1])
  79. xmax = np.minimum(x2, bbox[2])
  80. ymax = np.minimum(y2, bbox[3])
  81. w = np.maximum(xmax - xmin, 0.)
  82. h = np.maximum(ymax - ymin, 0.)
  83. # Volumes.
  84. inter_vol = h * w
  85. union_vol = vol_anchors + (bbox[2] - bbox[0]) * (bbox[3] - bbox[1]) - inter_vol
  86. jaccard = inter_vol / union_vol
  87. return np.squeeze(jaccard)
  88. pre_scores = np.zeros((config.NUM_SSD_BOXES), dtype=np.float32)
  89. t_boxes = np.zeros((config.NUM_SSD_BOXES, 4), dtype=np.float32)
  90. t_label = np.zeros((config.NUM_SSD_BOXES), dtype=np.int64)
  91. for bbox in boxes:
  92. label = int(bbox[4])
  93. scores = jaccard_with_anchors(bbox)
  94. mask = (scores > matching_threshold)
  95. if not np.any(mask):
  96. mask[np.argmax(scores)] = True
  97. mask = mask & (scores > pre_scores)
  98. pre_scores = np.maximum(pre_scores, scores)
  99. t_label = mask * label + (1 - mask) * t_label
  100. for i in range(4):
  101. t_boxes[:, i] = mask * bbox[i] + (1 - mask) * t_boxes[:, i]
  102. index = np.nonzero(t_label)
  103. # Transform to ltrb.
  104. bboxes = np.zeros((config.NUM_SSD_BOXES, 4), dtype=np.float32)
  105. bboxes[:, [0, 1]] = (t_boxes[:, [0, 1]] + t_boxes[:, [2, 3]]) / 2
  106. bboxes[:, [2, 3]] = t_boxes[:, [2, 3]] - t_boxes[:, [0, 1]]
  107. # Encode features.
  108. bboxes_t = bboxes[index]
  109. default_boxes_t = default_boxes[index]
  110. bboxes_t[:, :2] = (bboxes_t[:, :2] - default_boxes_t[:, :2]) / (default_boxes_t[:, 2:] * config.PRIOR_SCALING[0])
  111. bboxes_t[:, 2:4] = np.log(bboxes_t[:, 2:4] / default_boxes_t[:, 2:4]) / config.PRIOR_SCALING[1]
  112. bboxes[index] = bboxes_t
  113. num_match_num = np.array([len(np.nonzero(t_label)[0])], dtype=np.int32)
  114. return bboxes, t_label.astype(np.int32), num_match_num
  115. def ssd_bboxes_decode(boxes, index):
  116. """Decode predict boxes to [x, y, w, h]"""
  117. boxes_t = boxes[index]
  118. default_boxes_t = default_boxes[index]
  119. boxes_t[:, :2] = boxes_t[:, :2] * config.PRIOR_SCALING[0] * default_boxes_t[:, 2:] + default_boxes_t[:, :2]
  120. boxes_t[:, 2:4] = np.exp(boxes_t[:, 2:4] * config.PRIOR_SCALING[1]) * default_boxes_t[:, 2:4]
  121. bboxes = np.zeros((len(boxes_t), 4), dtype=np.float32)
  122. bboxes[:, [0, 1]] = boxes_t[:, [0, 1]] - boxes_t[:, [2, 3]] / 2
  123. bboxes[:, [2, 3]] = boxes_t[:, [0, 1]] + boxes_t[:, [2, 3]] / 2
  124. return bboxes
  125. def preprocess_fn(image, box, is_training):
  126. """Preprocess function for dataset."""
  127. def _rand(a=0., b=1.):
  128. """Generate random."""
  129. return np.random.rand() * (b - a) + a
  130. def _infer_data(image, input_shape, box):
  131. img_h, img_w, _ = image.shape
  132. input_h, input_w = input_shape
  133. scale = min(float(input_w) / float(img_w), float(input_h) / float(img_h))
  134. nw = int(img_w * scale)
  135. nh = int(img_h * scale)
  136. image = cv2.resize(image, (nw, nh))
  137. new_image = np.zeros((input_h, input_w, 3), np.float32)
  138. dh = (input_h - nh) // 2
  139. dw = (input_w - nw) // 2
  140. new_image[dh: (nh + dh), dw: (nw + dw), :] = image
  141. image = new_image
  142. #When the channels of image is 1
  143. if len(image.shape) == 2:
  144. image = np.expand_dims(image, axis=-1)
  145. image = np.concatenate([image, image, image], axis=-1)
  146. box = box.astype(np.float32)
  147. box[:, [0, 2]] = (box[:, [0, 2]] * scale + dw) / input_w
  148. box[:, [1, 3]] = (box[:, [1, 3]] * scale + dh) / input_h
  149. return image, np.array((img_h, img_w), np.float32), box
  150. def _data_aug(image, box, is_training, image_size=(300, 300)):
  151. """Data augmentation function."""
  152. ih, iw, _ = image.shape
  153. w, h = image_size
  154. if not is_training:
  155. return _infer_data(image, image_size, box)
  156. # Random settings
  157. scale_w = _rand(0.75, 1.25)
  158. scale_h = _rand(0.75, 1.25)
  159. flip = _rand() < .5
  160. nw = iw * scale_w
  161. nh = ih * scale_h
  162. scale = min(w / nw, h / nh)
  163. nw = int(scale * nw)
  164. nh = int(scale * nh)
  165. # Resize image
  166. image = cv2.resize(image, (nw, nh))
  167. # place image
  168. new_image = np.zeros((h, w, 3), dtype=np.float32)
  169. dw = (w - nw) // 2
  170. dh = (h - nh) // 2
  171. new_image[dh:dh + nh, dw:dw + nw, :] = image
  172. image = new_image
  173. # Flip image or not
  174. if flip:
  175. image = cv2.flip(image, 1, dst=None)
  176. # Convert image to gray or not
  177. gray = _rand() < .25
  178. if gray:
  179. image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  180. # When the channels of image is 1
  181. if len(image.shape) == 2:
  182. image = np.expand_dims(image, axis=-1)
  183. image = np.concatenate([image, image, image], axis=-1)
  184. box = box.astype(np.float32)
  185. # Transform box with shape[x1, y1, x2, y2].
  186. box[:, [0, 2]] = (box[:, [0, 2]] * scale * scale_w + dw) / w
  187. box[:, [1, 3]] = (box[:, [1, 3]] * scale * scale_h + dh) / h
  188. if flip:
  189. box[:, [0, 2]] = 1 - box[:, [2, 0]]
  190. box, label, num_match_num = ssd_bboxes_encode(box)
  191. return image, box, label, num_match_num
  192. return _data_aug(image, box, is_training, image_size=config.IMG_SHAPE)
  193. def create_coco_label(is_training):
  194. """Get image path and annotation from COCO."""
  195. from pycocotools.coco import COCO
  196. coco_root = config.COCO_ROOT
  197. data_type = config.VAL_DATA_TYPE
  198. if is_training:
  199. data_type = config.TRAIN_DATA_TYPE
  200. #Classes need to train or test.
  201. train_cls = config.COCO_CLASSES
  202. train_cls_dict = {}
  203. for i, cls in enumerate(train_cls):
  204. train_cls_dict[cls] = i
  205. anno_json = os.path.join(coco_root, config.INSTANCES_SET.format(data_type))
  206. coco = COCO(anno_json)
  207. classs_dict = {}
  208. cat_ids = coco.loadCats(coco.getCatIds())
  209. for cat in cat_ids:
  210. classs_dict[cat["id"]] = cat["name"]
  211. image_ids = coco.getImgIds()
  212. image_files = []
  213. image_anno_dict = {}
  214. for img_id in image_ids:
  215. image_info = coco.loadImgs(img_id)
  216. file_name = image_info[0]["file_name"]
  217. anno_ids = coco.getAnnIds(imgIds=img_id, iscrowd=None)
  218. anno = coco.loadAnns(anno_ids)
  219. image_path = os.path.join(coco_root, data_type, file_name)
  220. annos = []
  221. for label in anno:
  222. bbox = label["bbox"]
  223. class_name = classs_dict[label["category_id"]]
  224. if class_name in train_cls:
  225. x_min, x_max = bbox[0], bbox[0] + bbox[2]
  226. y_min, y_max = bbox[1], bbox[1] + bbox[3]
  227. annos.append(list(map(round, [x_min, y_min, x_max, y_max])) + [train_cls_dict[class_name]])
  228. if len(annos) >= 1:
  229. image_files.append(image_path)
  230. image_anno_dict[image_path] = np.array(annos)
  231. return image_files, image_anno_dict
  232. def anno_parser(annos_str):
  233. """Parse annotation from string to list."""
  234. annos = []
  235. for anno_str in annos_str:
  236. anno = list(map(int, anno_str.strip().split(',')))
  237. annos.append(anno)
  238. return annos
  239. def filter_valid_data(image_dir, anno_path):
  240. """Filter valid image file, which both in image_dir and anno_path."""
  241. image_files = []
  242. image_anno_dict = {}
  243. if not os.path.isdir(image_dir):
  244. raise RuntimeError("Path given is not valid.")
  245. if not os.path.isfile(anno_path):
  246. raise RuntimeError("Annotation file is not valid.")
  247. with open(anno_path, "rb") as f:
  248. lines = f.readlines()
  249. for line in lines:
  250. line_str = line.decode("utf-8").strip()
  251. line_split = str(line_str).split(' ')
  252. file_name = line_split[0]
  253. image_path = os.path.join(image_dir, file_name)
  254. if os.path.isfile(image_path):
  255. image_anno_dict[image_path] = anno_parser(line_split[1:])
  256. image_files.append(image_path)
  257. return image_files, image_anno_dict
  258. def data_to_mindrecord_byte_image(dataset="coco", is_training=True, prefix="ssd.mindrecord", file_num=8):
  259. """Create MindRecord file."""
  260. mindrecord_dir = config.MINDRECORD_DIR
  261. mindrecord_path = os.path.join(mindrecord_dir, prefix)
  262. writer = FileWriter(mindrecord_path, file_num)
  263. if dataset == "coco":
  264. image_files, image_anno_dict = create_coco_label(is_training)
  265. else:
  266. image_files, image_anno_dict = filter_valid_data(config.IMAGE_DIR, config.ANNO_PATH)
  267. ssd_json = {
  268. "image": {"type": "bytes"},
  269. "annotation": {"type": "int32", "shape": [-1, 5]},
  270. }
  271. writer.add_schema(ssd_json, "ssd_json")
  272. for image_name in image_files:
  273. with open(image_name, 'rb') as f:
  274. img = f.read()
  275. annos = np.array(image_anno_dict[image_name], dtype=np.int32)
  276. row = {"image": img, "annotation": annos}
  277. writer.write_raw_data([row])
  278. writer.commit()
  279. def create_ssd_dataset(mindrecord_file, batch_size=32, repeat_num=10, device_num=1, rank=0,
  280. is_training=True, num_parallel_workers=4):
  281. """Creatr SSD dataset with MindDataset."""
  282. ds = de.MindDataset(mindrecord_file, columns_list=["image", "annotation"], num_shards=device_num, shard_id=rank,
  283. num_parallel_workers=num_parallel_workers, shuffle=is_training)
  284. decode = C.Decode()
  285. ds = ds.map(input_columns=["image"], operations=decode)
  286. compose_map_func = (lambda image, annotation: preprocess_fn(image, annotation, is_training))
  287. if is_training:
  288. hwc_to_chw = C.HWC2CHW()
  289. ds = ds.map(input_columns=["image", "annotation"],
  290. output_columns=["image", "box", "label", "num_match_num"],
  291. columns_order=["image", "box", "label", "num_match_num"],
  292. operations=compose_map_func, python_multiprocessing=True, num_parallel_workers=num_parallel_workers)
  293. ds = ds.map(input_columns=["image"], operations=hwc_to_chw, python_multiprocessing=True,
  294. num_parallel_workers=num_parallel_workers)
  295. ds = ds.batch(batch_size, drop_remainder=True)
  296. ds = ds.repeat(repeat_num)
  297. else:
  298. hwc_to_chw = C.HWC2CHW()
  299. ds = ds.map(input_columns=["image", "annotation"],
  300. output_columns=["image", "image_shape", "annotation"],
  301. columns_order=["image", "image_shape", "annotation"],
  302. operations=compose_map_func)
  303. ds = ds.map(input_columns=["image"], operations=hwc_to_chw, num_parallel_workers=num_parallel_workers)
  304. ds = ds.batch(batch_size, drop_remainder=True)
  305. ds = ds.repeat(repeat_num)
  306. return ds