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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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 cv2
  19. import numpy as np
  20. import mindspore.dataset as de
  21. import mindspore.dataset.transforms.vision.c_transforms as C
  22. from mindspore.mindrecord import FileWriter
  23. from .config import config
  24. from .box_utils import jaccard_numpy, ssd_bboxes_encode
  25. def _rand(a=0., b=1.):
  26. """Generate random."""
  27. return np.random.rand() * (b - a) + a
  28. def random_sample_crop(image, boxes):
  29. """Random Crop the image and boxes"""
  30. height, width, _ = image.shape
  31. min_iou = np.random.choice([None, 0.1, 0.3, 0.5, 0.7, 0.9])
  32. if min_iou is None:
  33. return image, boxes
  34. # max trails (50)
  35. for _ in range(50):
  36. image_t = image
  37. w = _rand(0.3, 1.0) * width
  38. h = _rand(0.3, 1.0) * height
  39. # aspect ratio constraint b/t .5 & 2
  40. if h / w < 0.5 or h / w > 2:
  41. continue
  42. left = _rand() * (width - w)
  43. top = _rand() * (height - h)
  44. rect = np.array([int(top), int(left), int(top+h), int(left+w)])
  45. overlap = jaccard_numpy(boxes, rect)
  46. # dropout some boxes
  47. drop_mask = overlap > 0
  48. if not drop_mask.any():
  49. continue
  50. if overlap[drop_mask].min() < min_iou:
  51. continue
  52. image_t = image_t[rect[0]:rect[2], rect[1]:rect[3], :]
  53. centers = (boxes[:, :2] + boxes[:, 2:4]) / 2.0
  54. m1 = (rect[0] < centers[:, 0]) * (rect[1] < centers[:, 1])
  55. m2 = (rect[2] > centers[:, 0]) * (rect[3] > centers[:, 1])
  56. # mask in that both m1 and m2 are true
  57. mask = m1 * m2 * drop_mask
  58. # have any valid boxes? try again if not
  59. if not mask.any():
  60. continue
  61. # take only matching gt boxes
  62. boxes_t = boxes[mask, :].copy()
  63. boxes_t[:, :2] = np.maximum(boxes_t[:, :2], rect[:2])
  64. boxes_t[:, :2] -= rect[:2]
  65. boxes_t[:, 2:4] = np.minimum(boxes_t[:, 2:4], rect[2:4])
  66. boxes_t[:, 2:4] -= rect[:2]
  67. return image_t, boxes_t
  68. return image, boxes
  69. def preprocess_fn(img_id, image, box, is_training):
  70. """Preprocess function for dataset."""
  71. def _infer_data(image, input_shape):
  72. img_h, img_w, _ = image.shape
  73. input_h, input_w = input_shape
  74. image = cv2.resize(image, (input_w, input_h))
  75. #When the channels of image is 1
  76. if len(image.shape) == 2:
  77. image = np.expand_dims(image, axis=-1)
  78. image = np.concatenate([image, image, image], axis=-1)
  79. return img_id, image, np.array((img_h, img_w), np.float32)
  80. def _data_aug(image, box, is_training, image_size=(300, 300)):
  81. """Data augmentation function."""
  82. ih, iw, _ = image.shape
  83. w, h = image_size
  84. if not is_training:
  85. return _infer_data(image, image_size)
  86. # Random crop
  87. box = box.astype(np.float32)
  88. image, box = random_sample_crop(image, box)
  89. ih, iw, _ = image.shape
  90. # Resize image
  91. image = cv2.resize(image, (w, h))
  92. # Flip image or not
  93. flip = _rand() < .5
  94. if flip:
  95. image = cv2.flip(image, 1, dst=None)
  96. # When the channels of image is 1
  97. if len(image.shape) == 2:
  98. image = np.expand_dims(image, axis=-1)
  99. image = np.concatenate([image, image, image], axis=-1)
  100. box[:, [0, 2]] = box[:, [0, 2]] / ih
  101. box[:, [1, 3]] = box[:, [1, 3]] / iw
  102. if flip:
  103. box[:, [1, 3]] = 1 - box[:, [3, 1]]
  104. box, label, num_match = ssd_bboxes_encode(box)
  105. return image, box, label, num_match
  106. return _data_aug(image, box, is_training, image_size=config.img_shape)
  107. def create_coco_label(is_training):
  108. """Get image path and annotation from COCO."""
  109. from pycocotools.coco import COCO
  110. coco_root = config.coco_root
  111. data_type = config.val_data_type
  112. if is_training:
  113. data_type = config.train_data_type
  114. #Classes need to train or test.
  115. train_cls = config.coco_classes
  116. train_cls_dict = {}
  117. for i, cls in enumerate(train_cls):
  118. train_cls_dict[cls] = i
  119. anno_json = os.path.join(coco_root, config.instances_set.format(data_type))
  120. coco = COCO(anno_json)
  121. classs_dict = {}
  122. cat_ids = coco.loadCats(coco.getCatIds())
  123. for cat in cat_ids:
  124. classs_dict[cat["id"]] = cat["name"]
  125. image_ids = coco.getImgIds()
  126. images = []
  127. image_path_dict = {}
  128. image_anno_dict = {}
  129. for img_id in image_ids:
  130. image_info = coco.loadImgs(img_id)
  131. file_name = image_info[0]["file_name"]
  132. anno_ids = coco.getAnnIds(imgIds=img_id, iscrowd=None)
  133. anno = coco.loadAnns(anno_ids)
  134. image_path = os.path.join(coco_root, data_type, file_name)
  135. annos = []
  136. iscrowd = False
  137. for label in anno:
  138. bbox = label["bbox"]
  139. class_name = classs_dict[label["category_id"]]
  140. iscrowd = iscrowd or label["iscrowd"]
  141. if class_name in train_cls:
  142. x_min, x_max = bbox[0], bbox[0] + bbox[2]
  143. y_min, y_max = bbox[1], bbox[1] + bbox[3]
  144. annos.append(list(map(round, [y_min, x_min, y_max, x_max])) + [train_cls_dict[class_name]])
  145. if not is_training and iscrowd:
  146. continue
  147. if len(annos) >= 1:
  148. images.append(img_id)
  149. image_path_dict[img_id] = image_path
  150. image_anno_dict[img_id] = np.array(annos)
  151. return images, image_path_dict, image_anno_dict
  152. def anno_parser(annos_str):
  153. """Parse annotation from string to list."""
  154. annos = []
  155. for anno_str in annos_str:
  156. anno = list(map(int, anno_str.strip().split(',')))
  157. annos.append(anno)
  158. return annos
  159. def filter_valid_data(image_dir, anno_path):
  160. """Filter valid image file, which both in image_dir and anno_path."""
  161. images = []
  162. image_path_dict = {}
  163. image_anno_dict = {}
  164. if not os.path.isdir(image_dir):
  165. raise RuntimeError("Path given is not valid.")
  166. if not os.path.isfile(anno_path):
  167. raise RuntimeError("Annotation file is not valid.")
  168. with open(anno_path, "rb") as f:
  169. lines = f.readlines()
  170. for img_id, line in enumerate(lines):
  171. line_str = line.decode("utf-8").strip()
  172. line_split = str(line_str).split(' ')
  173. file_name = line_split[0]
  174. image_path = os.path.join(image_dir, file_name)
  175. if os.path.isfile(image_path):
  176. images.append(img_id)
  177. image_path_dict[img_id] = image_path
  178. image_anno_dict[img_id] = anno_parser(line_split[1:])
  179. return images, image_path_dict, image_anno_dict
  180. def data_to_mindrecord_byte_image(dataset="coco", is_training=True, prefix="ssd.mindrecord", file_num=8):
  181. """Create MindRecord file."""
  182. mindrecord_dir = config.mindrecord_dir
  183. mindrecord_path = os.path.join(mindrecord_dir, prefix)
  184. writer = FileWriter(mindrecord_path, file_num)
  185. if dataset == "coco":
  186. images, image_path_dict, image_anno_dict = create_coco_label(is_training)
  187. else:
  188. images, image_path_dict, image_anno_dict = filter_valid_data(config.image_dir, config.anno_path)
  189. ssd_json = {
  190. "img_id": {"type": "int32", "shape": [1]},
  191. "image": {"type": "bytes"},
  192. "annotation": {"type": "int32", "shape": [-1, 5]},
  193. }
  194. writer.add_schema(ssd_json, "ssd_json")
  195. for img_id in images:
  196. image_path = image_path_dict[img_id]
  197. with open(image_path, 'rb') as f:
  198. img = f.read()
  199. annos = np.array(image_anno_dict[img_id], dtype=np.int32)
  200. img_id = np.array([img_id], dtype=np.int32)
  201. row = {"img_id": img_id, "image": img, "annotation": annos}
  202. writer.write_raw_data([row])
  203. writer.commit()
  204. def create_ssd_dataset(mindrecord_file, batch_size=32, repeat_num=10, device_num=1, rank=0,
  205. is_training=True, num_parallel_workers=4):
  206. """Creatr SSD dataset with MindDataset."""
  207. ds = de.MindDataset(mindrecord_file, columns_list=["img_id", "image", "annotation"], num_shards=device_num,
  208. shard_id=rank, num_parallel_workers=num_parallel_workers, shuffle=is_training)
  209. decode = C.Decode()
  210. ds = ds.map(input_columns=["image"], operations=decode)
  211. change_swap_op = C.HWC2CHW()
  212. normalize_op = C.Normalize(mean=[0.485*255, 0.456*255, 0.406*255], std=[0.229*255, 0.224*255, 0.225*255])
  213. color_adjust_op = C.RandomColorAdjust(brightness=0.4, contrast=0.4, saturation=0.4)
  214. compose_map_func = (lambda img_id, image, annotation: preprocess_fn(img_id, image, annotation, is_training))
  215. if is_training:
  216. output_columns = ["image", "box", "label", "num_match"]
  217. trans = [color_adjust_op, normalize_op, change_swap_op]
  218. else:
  219. output_columns = ["img_id", "image", "image_shape"]
  220. trans = [normalize_op, change_swap_op]
  221. ds = ds.map(input_columns=["img_id", "image", "annotation"],
  222. output_columns=output_columns, columns_order=output_columns,
  223. operations=compose_map_func, python_multiprocessing=is_training,
  224. num_parallel_workers=num_parallel_workers)
  225. ds = ds.map(input_columns=["image"], operations=trans, python_multiprocessing=is_training,
  226. num_parallel_workers=num_parallel_workers)
  227. ds = ds.batch(batch_size, drop_remainder=True)
  228. ds = ds.repeat(repeat_num)
  229. return ds