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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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 json
  19. import xml.etree.ElementTree as et
  20. import numpy as np
  21. import cv2
  22. import mindspore.dataset as de
  23. import mindspore.dataset.vision.c_transforms as C
  24. from mindspore.mindrecord import FileWriter
  25. from .config import config
  26. from .box_utils import jaccard_numpy, ssd_bboxes_encode
  27. def _rand(a=0., b=1.):
  28. """Generate random."""
  29. return np.random.rand() * (b - a) + a
  30. def get_imageId_from_fileName(filename):
  31. """Get imageID from fileName"""
  32. try:
  33. filename = os.path.splitext(filename)[0]
  34. return int(filename)
  35. except:
  36. raise NotImplementedError('Filename %s is supposed to be an integer.'%(filename))
  37. def random_sample_crop(image, boxes):
  38. """Random Crop the image and boxes"""
  39. height, width, _ = image.shape
  40. min_iou = np.random.choice([None, 0.1, 0.3, 0.5, 0.7, 0.9])
  41. if min_iou is None:
  42. return image, boxes
  43. # max trails (50)
  44. for _ in range(50):
  45. image_t = image
  46. w = _rand(0.3, 1.0) * width
  47. h = _rand(0.3, 1.0) * height
  48. # aspect ratio constraint b/t .5 & 2
  49. if h / w < 0.5 or h / w > 2:
  50. continue
  51. left = _rand() * (width - w)
  52. top = _rand() * (height - h)
  53. rect = np.array([int(top), int(left), int(top+h), int(left+w)])
  54. overlap = jaccard_numpy(boxes, rect)
  55. # dropout some boxes
  56. drop_mask = overlap > 0
  57. if not drop_mask.any():
  58. continue
  59. if overlap[drop_mask].min() < min_iou and overlap[drop_mask].max() > (min_iou + 0.2):
  60. continue
  61. image_t = image_t[rect[0]:rect[2], rect[1]:rect[3], :]
  62. centers = (boxes[:, :2] + boxes[:, 2:4]) / 2.0
  63. m1 = (rect[0] < centers[:, 0]) * (rect[1] < centers[:, 1])
  64. m2 = (rect[2] > centers[:, 0]) * (rect[3] > centers[:, 1])
  65. # mask in that both m1 and m2 are true
  66. mask = m1 * m2 * drop_mask
  67. # have any valid boxes? try again if not
  68. if not mask.any():
  69. continue
  70. # take only matching gt boxes
  71. boxes_t = boxes[mask, :].copy()
  72. boxes_t[:, :2] = np.maximum(boxes_t[:, :2], rect[:2])
  73. boxes_t[:, :2] -= rect[:2]
  74. boxes_t[:, 2:4] = np.minimum(boxes_t[:, 2:4], rect[2:4])
  75. boxes_t[:, 2:4] -= rect[:2]
  76. return image_t, boxes_t
  77. return image, boxes
  78. def preprocess_fn(img_id, image, box, is_training):
  79. """Preprocess function for dataset."""
  80. def _infer_data(image, input_shape):
  81. img_h, img_w, _ = image.shape
  82. input_h, input_w = input_shape
  83. image = cv2.resize(image, (input_w, input_h))
  84. #When the channels of image is 1
  85. if len(image.shape) == 2:
  86. image = np.expand_dims(image, axis=-1)
  87. image = np.concatenate([image, image, image], axis=-1)
  88. return img_id, image, np.array((img_h, img_w), np.float32)
  89. def _data_aug(image, box, is_training, image_size=(300, 300)):
  90. """Data augmentation function."""
  91. ih, iw, _ = image.shape
  92. w, h = image_size
  93. if not is_training:
  94. return _infer_data(image, image_size)
  95. # Random crop
  96. box = box.astype(np.float32)
  97. image, box = random_sample_crop(image, box)
  98. ih, iw, _ = image.shape
  99. # Resize image
  100. image = cv2.resize(image, (w, h))
  101. # Flip image or not
  102. flip = _rand() < .5
  103. if flip:
  104. image = cv2.flip(image, 1, dst=None)
  105. # When the channels of image is 1
  106. if len(image.shape) == 2:
  107. image = np.expand_dims(image, axis=-1)
  108. image = np.concatenate([image, image, image], axis=-1)
  109. box[:, [0, 2]] = box[:, [0, 2]] / ih
  110. box[:, [1, 3]] = box[:, [1, 3]] / iw
  111. if flip:
  112. box[:, [1, 3]] = 1 - box[:, [3, 1]]
  113. box, label, num_match = ssd_bboxes_encode(box)
  114. return image, box, label, num_match
  115. return _data_aug(image, box, is_training, image_size=config.img_shape)
  116. def create_voc_label(is_training):
  117. """Get image path and annotation from VOC."""
  118. voc_dir = config.voc_dir
  119. cls_map = {name: i for i, name in enumerate(config.coco_classes)}
  120. sub_dir = 'train' if is_training else 'eval'
  121. #sub_dir = 'train'
  122. voc_dir = os.path.join(voc_dir, sub_dir)
  123. if not os.path.isdir(voc_dir):
  124. raise ValueError(f'Cannot find {sub_dir} dataset path.')
  125. image_dir = anno_dir = voc_dir
  126. if os.path.isdir(os.path.join(voc_dir, 'Images')):
  127. image_dir = os.path.join(voc_dir, 'Images')
  128. if os.path.isdir(os.path.join(voc_dir, 'Annotations')):
  129. anno_dir = os.path.join(voc_dir, 'Annotations')
  130. if not is_training:
  131. data_dir = config.voc_root
  132. json_file = os.path.join(data_dir, config.instances_set.format(sub_dir))
  133. file_dir = os.path.split(json_file)[0]
  134. if not os.path.isdir(file_dir):
  135. os.makedirs(file_dir)
  136. json_dict = {"images": [], "type": "instances", "annotations": [],
  137. "categories": []}
  138. bnd_id = 1
  139. image_files_dict = {}
  140. image_anno_dict = {}
  141. images = []
  142. for anno_file in os.listdir(anno_dir):
  143. print(anno_file)
  144. if not anno_file.endswith('xml'):
  145. continue
  146. tree = et.parse(os.path.join(anno_dir, anno_file))
  147. root_node = tree.getroot()
  148. file_name = root_node.find('filename').text
  149. img_id = get_imageId_from_fileName(file_name)
  150. image_path = os.path.join(image_dir, file_name)
  151. print(image_path)
  152. if not os.path.isfile(image_path):
  153. print(f'Cannot find image {file_name} according to annotations.')
  154. continue
  155. labels = []
  156. for obj in root_node.iter('object'):
  157. cls_name = obj.find('name').text
  158. if cls_name not in cls_map:
  159. print(f'Label "{cls_name}" not in "{config.coco_classes}"')
  160. continue
  161. bnd_box = obj.find('bndbox')
  162. x_min = int(bnd_box.find('xmin').text) - 1
  163. y_min = int(bnd_box.find('ymin').text) - 1
  164. x_max = int(bnd_box.find('xmax').text) - 1
  165. y_max = int(bnd_box.find('ymax').text) - 1
  166. labels.append([y_min, x_min, y_max, x_max, cls_map[cls_name]])
  167. if not is_training:
  168. o_width = abs(x_max - x_min)
  169. o_height = abs(y_max - y_min)
  170. ann = {'area': o_width * o_height, 'iscrowd': 0, 'image_id': \
  171. img_id, 'bbox': [x_min, y_min, o_width, o_height], \
  172. 'category_id': cls_map[cls_name], 'id': bnd_id, \
  173. 'ignore': 0, \
  174. 'segmentation': []}
  175. json_dict['annotations'].append(ann)
  176. bnd_id = bnd_id + 1
  177. if labels:
  178. images.append(img_id)
  179. image_files_dict[img_id] = image_path
  180. image_anno_dict[img_id] = np.array(labels)
  181. if not is_training:
  182. size = root_node.find("size")
  183. width = int(size.find('width').text)
  184. height = int(size.find('height').text)
  185. image = {'file_name': file_name, 'height': height, 'width': width,
  186. 'id': img_id}
  187. json_dict['images'].append(image)
  188. if not is_training:
  189. for cls_name, cid in cls_map.items():
  190. cat = {'supercategory': 'none', 'id': cid, 'name': cls_name}
  191. json_dict['categories'].append(cat)
  192. json_fp = open(json_file, 'w')
  193. json_str = json.dumps(json_dict)
  194. json_fp.write(json_str)
  195. json_fp.close()
  196. return images, image_files_dict, image_anno_dict
  197. def create_coco_label(is_training):
  198. """Get image path and annotation from COCO."""
  199. from pycocotools.coco import COCO
  200. coco_root = config.coco_root
  201. data_type = config.val_data_type
  202. if is_training:
  203. data_type = config.train_data_type
  204. #Classes need to train or test.
  205. train_cls = config.coco_classes
  206. train_cls_dict = {}
  207. for i, cls in enumerate(train_cls):
  208. train_cls_dict[cls] = i
  209. anno_json = os.path.join(coco_root, config.instances_set.format(data_type))
  210. coco = COCO(anno_json)
  211. classs_dict = {}
  212. cat_ids = coco.loadCats(coco.getCatIds())
  213. for cat in cat_ids:
  214. classs_dict[cat["id"]] = cat["name"]
  215. image_ids = coco.getImgIds()
  216. images = []
  217. image_path_dict = {}
  218. image_anno_dict = {}
  219. for img_id in image_ids:
  220. image_info = coco.loadImgs(img_id)
  221. file_name = image_info[0]["file_name"]
  222. anno_ids = coco.getAnnIds(imgIds=img_id, iscrowd=None)
  223. anno = coco.loadAnns(anno_ids)
  224. image_path = os.path.join(coco_root, data_type, file_name)
  225. annos = []
  226. iscrowd = False
  227. for label in anno:
  228. bbox = label["bbox"]
  229. class_name = classs_dict[label["category_id"]]
  230. iscrowd = iscrowd or label["iscrowd"]
  231. if class_name in train_cls:
  232. x_min, x_max = bbox[0], bbox[0] + bbox[2]
  233. y_min, y_max = bbox[1], bbox[1] + bbox[3]
  234. annos.append(list(map(round, [y_min, x_min, y_max, x_max])) + [train_cls_dict[class_name]])
  235. if not is_training and iscrowd:
  236. continue
  237. if len(annos) >= 1:
  238. images.append(img_id)
  239. image_path_dict[img_id] = image_path
  240. image_anno_dict[img_id] = np.array(annos)
  241. return images, image_path_dict, image_anno_dict
  242. def anno_parser(annos_str):
  243. """Parse annotation from string to list."""
  244. annos = []
  245. for anno_str in annos_str:
  246. anno = list(map(int, anno_str.strip().split(',')))
  247. annos.append(anno)
  248. return annos
  249. def filter_valid_data(image_dir, anno_path):
  250. """Filter valid image file, which both in image_dir and anno_path."""
  251. images = []
  252. image_path_dict = {}
  253. image_anno_dict = {}
  254. if not os.path.isdir(image_dir):
  255. raise RuntimeError("Path given is not valid.")
  256. if not os.path.isfile(anno_path):
  257. raise RuntimeError("Annotation file is not valid.")
  258. with open(anno_path, "rb") as f:
  259. lines = f.readlines()
  260. for img_id, line in enumerate(lines):
  261. line_str = line.decode("utf-8").strip()
  262. line_split = str(line_str).split(' ')
  263. file_name = line_split[0]
  264. image_path = os.path.join(image_dir, file_name)
  265. if os.path.isfile(image_path):
  266. images.append(img_id)
  267. image_path_dict[img_id] = image_path
  268. image_anno_dict[img_id] = anno_parser(line_split[1:])
  269. return images, image_path_dict, image_anno_dict
  270. def voc_data_to_mindrecord(mindrecord_dir, is_training, prefix="ssd.mindrecord", file_num=8):
  271. """Create MindRecord file by image_dir and anno_path."""
  272. mindrecord_path = os.path.join(mindrecord_dir, prefix)
  273. writer = FileWriter(mindrecord_path, file_num)
  274. images, image_path_dict, image_anno_dict = create_voc_label(is_training)
  275. ssd_json = {
  276. "img_id": {"type": "int32", "shape": [1]},
  277. "image": {"type": "bytes"},
  278. "annotation": {"type": "int32", "shape": [-1, 5]},
  279. }
  280. writer.add_schema(ssd_json, "ssd_json")
  281. for img_id in images:
  282. image_path = image_path_dict[img_id]
  283. with open(image_path, 'rb') as f:
  284. img = f.read()
  285. annos = np.array(image_anno_dict[img_id], dtype=np.int32)
  286. img_id = np.array([img_id], dtype=np.int32)
  287. row = {"img_id": img_id, "image": img, "annotation": annos}
  288. writer.write_raw_data([row])
  289. writer.commit()
  290. def data_to_mindrecord_byte_image(dataset="coco", is_training=True, prefix="ssd.mindrecord", file_num=8):
  291. """Create MindRecord file."""
  292. mindrecord_dir = config.mindrecord_dir
  293. mindrecord_path = os.path.join(mindrecord_dir, prefix)
  294. writer = FileWriter(mindrecord_path, file_num)
  295. if dataset == "coco":
  296. images, image_path_dict, image_anno_dict = create_coco_label(is_training)
  297. else:
  298. images, image_path_dict, image_anno_dict = filter_valid_data(config.image_dir, config.anno_path)
  299. ssd_json = {
  300. "img_id": {"type": "int32", "shape": [1]},
  301. "image": {"type": "bytes"},
  302. "annotation": {"type": "int32", "shape": [-1, 5]},
  303. }
  304. writer.add_schema(ssd_json, "ssd_json")
  305. for img_id in images:
  306. image_path = image_path_dict[img_id]
  307. with open(image_path, 'rb') as f:
  308. img = f.read()
  309. annos = np.array(image_anno_dict[img_id], dtype=np.int32)
  310. img_id = np.array([img_id], dtype=np.int32)
  311. row = {"img_id": img_id, "image": img, "annotation": annos}
  312. writer.write_raw_data([row])
  313. writer.commit()
  314. def create_ssd_dataset(mindrecord_file, batch_size=32, repeat_num=10, device_num=1, rank=0,
  315. is_training=True, num_parallel_workers=4):
  316. """Creatr SSD dataset with MindDataset."""
  317. ds = de.MindDataset(mindrecord_file, columns_list=["img_id", "image", "annotation"], num_shards=device_num,
  318. shard_id=rank, num_parallel_workers=num_parallel_workers, shuffle=is_training)
  319. decode = C.Decode()
  320. ds = ds.map(input_columns=["image"], operations=decode)
  321. change_swap_op = C.HWC2CHW()
  322. normalize_op = C.Normalize(mean=[0.485*255, 0.456*255, 0.406*255], std=[0.229*255, 0.224*255, 0.225*255])
  323. color_adjust_op = C.RandomColorAdjust(brightness=0.4, contrast=0.4, saturation=0.4)
  324. compose_map_func = (lambda img_id, image, annotation: preprocess_fn(img_id, image, annotation, is_training))
  325. if is_training:
  326. output_columns = ["image", "box", "label", "num_match"]
  327. trans = [color_adjust_op, normalize_op, change_swap_op]
  328. else:
  329. output_columns = ["img_id", "image", "image_shape"]
  330. trans = [normalize_op, change_swap_op]
  331. ds = ds.map(input_columns=["img_id", "image", "annotation"],
  332. output_columns=output_columns, column_order=output_columns,
  333. operations=compose_map_func, python_multiprocessing=is_training,
  334. num_parallel_workers=num_parallel_workers)
  335. ds = ds.map(input_columns=["image"], operations=trans, python_multiprocessing=is_training,
  336. num_parallel_workers=num_parallel_workers)
  337. ds = ds.batch(batch_size, drop_remainder=True)
  338. ds = ds.repeat(repeat_num)
  339. return ds