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

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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 [y, x, h, w].
  31. `self.default_boxes_ltrb` has a shape as `self.default_boxes`, the last dimension is [y1, x1, y2, x2].
  32. """
  33. def __init__(self):
  34. fk = config.IMG_SHAPE[0] / np.array(config.STEPS)
  35. scale_rate = (config.MAX_SCALE - config.MIN_SCALE) / (len(config.NUM_DEFAULT) - 1)
  36. scales = [config.MIN_SCALE + scale_rate * i for i in range(len(config.NUM_DEFAULT))] + [1.0]
  37. self.default_boxes = []
  38. for idex, feature_size in enumerate(config.FEATURE_SIZE):
  39. sk1 = scales[idex]
  40. sk2 = scales[idex + 1]
  41. sk3 = math.sqrt(sk1 * sk2)
  42. if idex == 0:
  43. w, h = sk1 * math.sqrt(2), sk1 / math.sqrt(2)
  44. all_sizes = [(0.1, 0.1), (w, h), (h, w)]
  45. else:
  46. all_sizes = [(sk1, sk1)]
  47. for aspect_ratio in config.ASPECT_RATIOS[idex]:
  48. w, h = sk1 * math.sqrt(aspect_ratio), sk1 / math.sqrt(aspect_ratio)
  49. all_sizes.append((w, h))
  50. all_sizes.append((h, w))
  51. all_sizes.append((sk3, sk3))
  52. assert len(all_sizes) == config.NUM_DEFAULT[idex]
  53. for i, j in it.product(range(feature_size), repeat=2):
  54. for w, h in all_sizes:
  55. cx, cy = (j + 0.5) / fk[idex], (i + 0.5) / fk[idex]
  56. self.default_boxes.append([cy, cx, h, w])
  57. def to_ltrb(cy, cx, h, w):
  58. return cy - h / 2, cx - w / 2, cy + h / 2, cx + w / 2
  59. # For IoU calculation
  60. self.default_boxes_ltrb = np.array(tuple(to_ltrb(*i) for i in self.default_boxes), dtype='float32')
  61. self.default_boxes = np.array(self.default_boxes, dtype='float32')
  62. default_boxes_ltrb = GeneratDefaultBoxes().default_boxes_ltrb
  63. default_boxes = GeneratDefaultBoxes().default_boxes
  64. y1, x1, y2, x2 = np.split(default_boxes_ltrb[:, :4], 4, axis=-1)
  65. vol_anchors = (x2 - x1) * (y2 - y1)
  66. matching_threshold = config.MATCH_THRESHOLD
  67. def _rand(a=0., b=1.):
  68. """Generate random."""
  69. return np.random.rand() * (b - a) + a
  70. def ssd_bboxes_encode(boxes):
  71. """
  72. Labels anchors with ground truth inputs.
  73. Args:
  74. boxex: ground truth with shape [N, 5], for each row, it stores [y, x, h, w, cls].
  75. Returns:
  76. gt_loc: location ground truth with shape [num_anchors, 4].
  77. gt_label: class ground truth with shape [num_anchors, 1].
  78. num_matched_boxes: number of positives in an image.
  79. """
  80. def jaccard_with_anchors(bbox):
  81. """Compute jaccard score a box and the anchors."""
  82. # Intersection bbox and volume.
  83. ymin = np.maximum(y1, bbox[0])
  84. xmin = np.maximum(x1, bbox[1])
  85. ymax = np.minimum(y2, bbox[2])
  86. xmax = np.minimum(x2, bbox[3])
  87. w = np.maximum(xmax - xmin, 0.)
  88. h = np.maximum(ymax - ymin, 0.)
  89. # Volumes.
  90. inter_vol = h * w
  91. union_vol = vol_anchors + (bbox[2] - bbox[0]) * (bbox[3] - bbox[1]) - inter_vol
  92. jaccard = inter_vol / union_vol
  93. return np.squeeze(jaccard)
  94. pre_scores = np.zeros((config.NUM_SSD_BOXES), dtype=np.float32)
  95. t_boxes = np.zeros((config.NUM_SSD_BOXES, 4), dtype=np.float32)
  96. t_label = np.zeros((config.NUM_SSD_BOXES), dtype=np.int64)
  97. for bbox in boxes:
  98. label = int(bbox[4])
  99. scores = jaccard_with_anchors(bbox)
  100. idx = np.argmax(scores)
  101. scores[idx] = 2.0
  102. mask = (scores > matching_threshold)
  103. mask = mask & (scores > pre_scores)
  104. pre_scores = np.maximum(pre_scores, scores * mask)
  105. t_label = mask * label + (1 - mask) * t_label
  106. for i in range(4):
  107. t_boxes[:, i] = mask * bbox[i] + (1 - mask) * t_boxes[:, i]
  108. index = np.nonzero(t_label)
  109. # Transform to ltrb.
  110. bboxes = np.zeros((config.NUM_SSD_BOXES, 4), dtype=np.float32)
  111. bboxes[:, [0, 1]] = (t_boxes[:, [0, 1]] + t_boxes[:, [2, 3]]) / 2
  112. bboxes[:, [2, 3]] = t_boxes[:, [2, 3]] - t_boxes[:, [0, 1]]
  113. # Encode features.
  114. bboxes_t = bboxes[index]
  115. default_boxes_t = default_boxes[index]
  116. bboxes_t[:, :2] = (bboxes_t[:, :2] - default_boxes_t[:, :2]) / (default_boxes_t[:, 2:] * config.PRIOR_SCALING[0])
  117. bboxes_t[:, 2:4] = np.log(bboxes_t[:, 2:4] / default_boxes_t[:, 2:4]) / config.PRIOR_SCALING[1]
  118. bboxes[index] = bboxes_t
  119. num_match = np.array([len(np.nonzero(t_label)[0])], dtype=np.int32)
  120. return bboxes, t_label.astype(np.int32), num_match
  121. def ssd_bboxes_decode(boxes):
  122. """Decode predict boxes to [y, x, h, w]"""
  123. boxes_t = boxes.copy()
  124. default_boxes_t = default_boxes.copy()
  125. boxes_t[:, :2] = boxes_t[:, :2] * config.PRIOR_SCALING[0] * default_boxes_t[:, 2:] + default_boxes_t[:, :2]
  126. boxes_t[:, 2:4] = np.exp(boxes_t[:, 2:4] * config.PRIOR_SCALING[1]) * default_boxes_t[:, 2:4]
  127. bboxes = np.zeros((len(boxes_t), 4), dtype=np.float32)
  128. bboxes[:, [0, 1]] = boxes_t[:, [0, 1]] - boxes_t[:, [2, 3]] / 2
  129. bboxes[:, [2, 3]] = boxes_t[:, [0, 1]] + boxes_t[:, [2, 3]] / 2
  130. return np.clip(bboxes, 0, 1)
  131. def intersect(box_a, box_b):
  132. """Compute the intersect of two sets of boxes."""
  133. max_yx = np.minimum(box_a[:, 2:4], box_b[2:4])
  134. min_yx = np.maximum(box_a[:, :2], box_b[:2])
  135. inter = np.clip((max_yx - min_yx), a_min=0, a_max=np.inf)
  136. return inter[:, 0] * inter[:, 1]
  137. def jaccard_numpy(box_a, box_b):
  138. """Compute the jaccard overlap of two sets of boxes."""
  139. inter = intersect(box_a, box_b)
  140. area_a = ((box_a[:, 2] - box_a[:, 0]) *
  141. (box_a[:, 3] - box_a[:, 1]))
  142. area_b = ((box_b[2] - box_b[0]) *
  143. (box_b[3] - box_b[1]))
  144. union = area_a + area_b - inter
  145. return inter / union
  146. def random_sample_crop(image, boxes):
  147. """Random Crop the image and boxes"""
  148. height, width, _ = image.shape
  149. min_iou = np.random.choice([None, 0.1, 0.3, 0.5, 0.7, 0.9])
  150. if min_iou is None:
  151. return image, boxes
  152. # max trails (50)
  153. for _ in range(50):
  154. image_t = image
  155. w = _rand(0.3, 1.0) * width
  156. h = _rand(0.3, 1.0) * height
  157. # aspect ratio constraint b/t .5 & 2
  158. if h / w < 0.5 or h / w > 2:
  159. continue
  160. left = _rand() * (width - w)
  161. top = _rand() * (height - h)
  162. rect = np.array([int(top), int(left), int(top+h), int(left+w)])
  163. overlap = jaccard_numpy(boxes, rect)
  164. # dropout some boxes
  165. drop_mask = overlap > 0
  166. if not drop_mask.any():
  167. continue
  168. if overlap[drop_mask].min() < min_iou:
  169. continue
  170. image_t = image_t[rect[0]:rect[2], rect[1]:rect[3], :]
  171. centers = (boxes[:, :2] + boxes[:, 2:4]) / 2.0
  172. m1 = (rect[0] < centers[:, 0]) * (rect[1] < centers[:, 1])
  173. m2 = (rect[2] > centers[:, 0]) * (rect[3] > centers[:, 1])
  174. # mask in that both m1 and m2 are true
  175. mask = m1 * m2 * drop_mask
  176. # have any valid boxes? try again if not
  177. if not mask.any():
  178. continue
  179. # take only matching gt boxes
  180. boxes_t = boxes[mask, :].copy()
  181. boxes_t[:, :2] = np.maximum(boxes_t[:, :2], rect[:2])
  182. boxes_t[:, :2] -= rect[:2]
  183. boxes_t[:, 2:4] = np.minimum(boxes_t[:, 2:4], rect[2:4])
  184. boxes_t[:, 2:4] -= rect[:2]
  185. return image_t, boxes_t
  186. return image, boxes
  187. def preprocess_fn(img_id, image, box, is_training):
  188. """Preprocess function for dataset."""
  189. def _infer_data(image, input_shape):
  190. img_h, img_w, _ = image.shape
  191. input_h, input_w = input_shape
  192. image = cv2.resize(image, (input_w, input_h))
  193. #When the channels of image is 1
  194. if len(image.shape) == 2:
  195. image = np.expand_dims(image, axis=-1)
  196. image = np.concatenate([image, image, image], axis=-1)
  197. return img_id, image, np.array((img_h, img_w), np.float32)
  198. def _data_aug(image, box, is_training, image_size=(300, 300)):
  199. """Data augmentation function."""
  200. ih, iw, _ = image.shape
  201. w, h = image_size
  202. if not is_training:
  203. return _infer_data(image, image_size)
  204. # Random crop
  205. box = box.astype(np.float32)
  206. image, box = random_sample_crop(image, box)
  207. ih, iw, _ = image.shape
  208. # Resize image
  209. image = cv2.resize(image, (w, h))
  210. # Flip image or not
  211. flip = _rand() < .5
  212. if flip:
  213. image = cv2.flip(image, 1, dst=None)
  214. # When the channels of image is 1
  215. if len(image.shape) == 2:
  216. image = np.expand_dims(image, axis=-1)
  217. image = np.concatenate([image, image, image], axis=-1)
  218. box[:, [0, 2]] = box[:, [0, 2]] / ih
  219. box[:, [1, 3]] = box[:, [1, 3]] / iw
  220. if flip:
  221. box[:, [1, 3]] = 1 - box[:, [3, 1]]
  222. box, label, num_match = ssd_bboxes_encode(box)
  223. return image, box, label, num_match
  224. return _data_aug(image, box, is_training, image_size=config.IMG_SHAPE)
  225. def create_coco_label(is_training):
  226. """Get image path and annotation from COCO."""
  227. from pycocotools.coco import COCO
  228. coco_root = config.COCO_ROOT
  229. data_type = config.VAL_DATA_TYPE
  230. if is_training:
  231. data_type = config.TRAIN_DATA_TYPE
  232. #Classes need to train or test.
  233. train_cls = config.COCO_CLASSES
  234. train_cls_dict = {}
  235. for i, cls in enumerate(train_cls):
  236. train_cls_dict[cls] = i
  237. anno_json = os.path.join(coco_root, config.INSTANCES_SET.format(data_type))
  238. coco = COCO(anno_json)
  239. classs_dict = {}
  240. cat_ids = coco.loadCats(coco.getCatIds())
  241. for cat in cat_ids:
  242. classs_dict[cat["id"]] = cat["name"]
  243. image_ids = coco.getImgIds()
  244. images = []
  245. image_path_dict = {}
  246. image_anno_dict = {}
  247. for img_id in image_ids:
  248. image_info = coco.loadImgs(img_id)
  249. file_name = image_info[0]["file_name"]
  250. anno_ids = coco.getAnnIds(imgIds=img_id, iscrowd=None)
  251. anno = coco.loadAnns(anno_ids)
  252. image_path = os.path.join(coco_root, data_type, file_name)
  253. annos = []
  254. iscrowd = False
  255. for label in anno:
  256. bbox = label["bbox"]
  257. class_name = classs_dict[label["category_id"]]
  258. iscrowd = iscrowd or label["iscrowd"]
  259. if class_name in train_cls:
  260. x_min, x_max = bbox[0], bbox[0] + bbox[2]
  261. y_min, y_max = bbox[1], bbox[1] + bbox[3]
  262. annos.append(list(map(round, [y_min, x_min, y_max, x_max])) + [train_cls_dict[class_name]])
  263. if not is_training and iscrowd:
  264. continue
  265. if len(annos) >= 1:
  266. images.append(img_id)
  267. image_path_dict[img_id] = image_path
  268. image_anno_dict[img_id] = np.array(annos)
  269. return images, image_path_dict, image_anno_dict
  270. def anno_parser(annos_str):
  271. """Parse annotation from string to list."""
  272. annos = []
  273. for anno_str in annos_str:
  274. anno = list(map(int, anno_str.strip().split(',')))
  275. annos.append(anno)
  276. return annos
  277. def filter_valid_data(image_dir, anno_path):
  278. """Filter valid image file, which both in image_dir and anno_path."""
  279. images = []
  280. image_path_dict = {}
  281. image_anno_dict = {}
  282. if not os.path.isdir(image_dir):
  283. raise RuntimeError("Path given is not valid.")
  284. if not os.path.isfile(anno_path):
  285. raise RuntimeError("Annotation file is not valid.")
  286. with open(anno_path, "rb") as f:
  287. lines = f.readlines()
  288. for img_id, line in enumerate(lines):
  289. line_str = line.decode("utf-8").strip()
  290. line_split = str(line_str).split(' ')
  291. file_name = line_split[0]
  292. image_path = os.path.join(image_dir, file_name)
  293. if os.path.isfile(image_path):
  294. images.append(img_id)
  295. image_path_dict[img_id] = image_path
  296. image_anno_dict[img_id] = anno_parser(line_split[1:])
  297. return images, image_path_dict, image_anno_dict
  298. def data_to_mindrecord_byte_image(dataset="coco", is_training=True, prefix="ssd.mindrecord", file_num=8):
  299. """Create MindRecord file."""
  300. mindrecord_dir = config.MINDRECORD_DIR
  301. mindrecord_path = os.path.join(mindrecord_dir, prefix)
  302. writer = FileWriter(mindrecord_path, file_num)
  303. if dataset == "coco":
  304. images, image_path_dict, image_anno_dict = create_coco_label(is_training)
  305. else:
  306. images, image_path_dict, image_anno_dict = filter_valid_data(config.IMAGE_DIR, config.ANNO_PATH)
  307. ssd_json = {
  308. "img_id": {"type": "int32", "shape": [1]},
  309. "image": {"type": "bytes"},
  310. "annotation": {"type": "int32", "shape": [-1, 5]},
  311. }
  312. writer.add_schema(ssd_json, "ssd_json")
  313. for img_id in images:
  314. image_path = image_path_dict[img_id]
  315. with open(image_path, 'rb') as f:
  316. img = f.read()
  317. annos = np.array(image_anno_dict[img_id], dtype=np.int32)
  318. img_id = np.array([img_id], dtype=np.int32)
  319. row = {"img_id": img_id, "image": img, "annotation": annos}
  320. writer.write_raw_data([row])
  321. writer.commit()
  322. def create_ssd_dataset(mindrecord_file, batch_size=32, repeat_num=10, device_num=1, rank=0,
  323. is_training=True, num_parallel_workers=4):
  324. """Creatr SSD dataset with MindDataset."""
  325. ds = de.MindDataset(mindrecord_file, columns_list=["img_id", "image", "annotation"], num_shards=device_num,
  326. shard_id=rank, num_parallel_workers=num_parallel_workers, shuffle=is_training)
  327. decode = C.Decode()
  328. ds = ds.map(input_columns=["image"], operations=decode)
  329. change_swap_op = C.HWC2CHW()
  330. normalize_op = C.Normalize(mean=[0.485*255, 0.456*255, 0.406*255], std=[0.229*255, 0.224*255, 0.225*255])
  331. color_adjust_op = C.RandomColorAdjust(brightness=0.4, contrast=0.4, saturation=0.4)
  332. compose_map_func = (lambda img_id, image, annotation: preprocess_fn(img_id, image, annotation, is_training))
  333. if is_training:
  334. output_columns = ["image", "box", "label", "num_match"]
  335. trans = [color_adjust_op, normalize_op, change_swap_op]
  336. else:
  337. output_columns = ["img_id", "image", "image_shape"]
  338. trans = [normalize_op, change_swap_op]
  339. ds = ds.map(input_columns=["img_id", "image", "annotation"],
  340. output_columns=output_columns, columns_order=output_columns,
  341. operations=compose_map_func, python_multiprocessing=is_training,
  342. num_parallel_workers=num_parallel_workers)
  343. ds = ds.map(input_columns=["image"], operations=trans, python_multiprocessing=is_training,
  344. num_parallel_workers=num_parallel_workers)
  345. ds = ds.batch(batch_size, drop_remainder=True)
  346. ds = ds.repeat(repeat_num)
  347. return ds