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

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. # Copyright 2021 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. """retinanet 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, retinanet_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. filename = os.path.splitext(filename)[0]
  33. if filename.isdigit():
  34. return int(filename)
  35. return id_iter
  36. def random_sample_crop(image, boxes):
  37. """Random Crop the image and boxes"""
  38. height, width, _ = image.shape
  39. min_iou = np.random.choice([None, 0.1, 0.3, 0.5, 0.7, 0.9])
  40. if min_iou is None:
  41. return image, boxes
  42. # max trails (50)
  43. for _ in range(50):
  44. image_t = image
  45. w = _rand(0.3, 1.0) * width
  46. h = _rand(0.3, 1.0) * height
  47. # aspect ratio constraint b/t .5 & 2
  48. if h / w < 0.5 or h / w > 2:
  49. continue
  50. left = _rand() * (width - w)
  51. top = _rand() * (height - h)
  52. rect = np.array([int(top), int(left), int(top + h), int(left + w)])
  53. overlap = jaccard_numpy(boxes, rect)
  54. # dropout some boxes
  55. drop_mask = overlap > 0
  56. if not drop_mask.any():
  57. continue
  58. if overlap[drop_mask].min() < min_iou and overlap[drop_mask].max() > (min_iou + 0.2):
  59. continue
  60. image_t = image_t[rect[0]:rect[2], rect[1]:rect[3], :]
  61. centers = (boxes[:, :2] + boxes[:, 2:4]) / 2.0
  62. m1 = (rect[0] < centers[:, 0]) * (rect[1] < centers[:, 1])
  63. m2 = (rect[2] > centers[:, 0]) * (rect[3] > centers[:, 1])
  64. # mask in that both m1 and m2 are true
  65. mask = m1 * m2 * drop_mask
  66. # have any valid boxes? try again if not
  67. if not mask.any():
  68. continue
  69. # take only matching gt boxes
  70. boxes_t = boxes[mask, :].copy()
  71. boxes_t[:, :2] = np.maximum(boxes_t[:, :2], rect[:2])
  72. boxes_t[:, :2] -= rect[:2]
  73. boxes_t[:, 2:4] = np.minimum(boxes_t[:, 2:4], rect[2:4])
  74. boxes_t[:, 2:4] -= rect[:2]
  75. return image_t, boxes_t
  76. return image, boxes
  77. def preprocess_fn(img_id, image, box, is_training):
  78. """Preprocess function for dataset."""
  79. cv2.setNumThreads(2)
  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=(600, 600)):
  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 = retinanet_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. voc_dir = os.path.join(voc_dir, sub_dir)
  122. if not os.path.isdir(voc_dir):
  123. raise ValueError(f'Cannot find {sub_dir} dataset path.')
  124. image_dir = anno_dir = voc_dir
  125. if os.path.isdir(os.path.join(voc_dir, 'Images')):
  126. image_dir = os.path.join(voc_dir, 'Images')
  127. if os.path.isdir(os.path.join(voc_dir, 'Annotations')):
  128. anno_dir = os.path.join(voc_dir, 'Annotations')
  129. if not is_training:
  130. data_dir = config.voc_root
  131. json_file = os.path.join(data_dir, config.instances_set.format(sub_dir))
  132. file_dir = os.path.split(json_file)[0]
  133. if not os.path.isdir(file_dir):
  134. os.makedirs(file_dir)
  135. json_dict = {"images": [], "type": "instances", "annotations": [],
  136. "categories": []}
  137. bnd_id = 1
  138. image_files_dict = {}
  139. image_anno_dict = {}
  140. images = []
  141. for anno_file in os.listdir(anno_dir):
  142. print(anno_file)
  143. if not anno_file.endswith('xml'):
  144. continue
  145. tree = et.parse(os.path.join(anno_dir, anno_file))
  146. root_node = tree.getroot()
  147. file_name = root_node.find('filename').text
  148. img_id = get_imageId_from_fileName(file_name)
  149. image_path = os.path.join(image_dir, file_name)
  150. print(image_path)
  151. if not os.path.isfile(image_path):
  152. print(f'Cannot find image {file_name} according to annotations.')
  153. continue
  154. labels = []
  155. for obj in root_node.iter('object'):
  156. cls_name = obj.find('name').text
  157. if cls_name not in cls_map:
  158. print(f'Label "{cls_name}" not in "{config.coco_classes}"')
  159. continue
  160. bnd_box = obj.find('bndbox')
  161. x_min = int(float(bnd_box.find('xmin').text)) - 1
  162. y_min = int(float(bnd_box.find('ymin').text)) - 1
  163. x_max = int(float(bnd_box.find('xmax').text)) - 1
  164. y_max = int(float(bnd_box.find('ymax').text)) - 1
  165. labels.append([y_min, x_min, y_max, x_max, cls_map[cls_name]])
  166. if not is_training:
  167. o_width = abs(x_max - x_min)
  168. o_height = abs(y_max - y_min)
  169. ann = {'area': o_width * o_height, 'iscrowd': 0, 'image_id': \
  170. img_id, 'bbox': [x_min, y_min, o_width, o_height], \
  171. 'category_id': cls_map[cls_name], 'id': bnd_id, \
  172. 'ignore': 0, \
  173. 'segmentation': []}
  174. json_dict['annotations'].append(ann)
  175. bnd_id = bnd_id + 1
  176. if labels:
  177. images.append(img_id)
  178. image_files_dict[img_id] = image_path
  179. image_anno_dict[img_id] = np.array(labels)
  180. if not is_training:
  181. size = root_node.find("size")
  182. width = int(size.find('width').text)
  183. height = int(size.find('height').text)
  184. image = {'file_name': file_name, 'height': height, 'width': width,
  185. 'id': img_id}
  186. json_dict['images'].append(image)
  187. if not is_training:
  188. for cls_name, cid in cls_map.items():
  189. cat = {'supercategory': 'none', 'id': cid, 'name': cls_name}
  190. json_dict['categories'].append(cat)
  191. json_fp = open(json_file, 'w')
  192. json_str = json.dumps(json_dict)
  193. json_fp.write(json_str)
  194. json_fp.close()
  195. return images, image_files_dict, image_anno_dict
  196. def create_coco_label(is_training):
  197. """Get image path and annotation from COCO."""
  198. from pycocotools.coco import COCO
  199. coco_root = config.coco_root
  200. data_type = config.val_data_type
  201. if is_training:
  202. data_type = config.train_data_type
  203. # Classes need to train or test.
  204. train_cls = config.coco_classes
  205. train_cls_dict = {}
  206. for i, cls in enumerate(train_cls):
  207. train_cls_dict[cls] = i
  208. anno_json = os.path.join(coco_root, config.instances_set.format(data_type))
  209. coco = COCO(anno_json)
  210. classs_dict = {}
  211. cat_ids = coco.loadCats(coco.getCatIds())
  212. for cat in cat_ids:
  213. classs_dict[cat["id"]] = cat["name"]
  214. image_ids = coco.getImgIds()
  215. images = []
  216. image_path_dict = {}
  217. image_anno_dict = {}
  218. for img_id in image_ids:
  219. image_info = coco.loadImgs(img_id)
  220. file_name = image_info[0]["file_name"]
  221. anno_ids = coco.getAnnIds(imgIds=img_id, iscrowd=None)
  222. anno = coco.loadAnns(anno_ids)
  223. image_path = os.path.join(coco_root, data_type, file_name)
  224. annos = []
  225. iscrowd = False
  226. for label in anno:
  227. bbox = label["bbox"]
  228. class_name = classs_dict[label["category_id"]]
  229. iscrowd = iscrowd or label["iscrowd"]
  230. if class_name in train_cls:
  231. x_min, x_max = bbox[0], bbox[0] + bbox[2]
  232. y_min, y_max = bbox[1], bbox[1] + bbox[3]
  233. annos.append(list(map(round, [y_min, x_min, y_max, x_max])) + [train_cls_dict[class_name]])
  234. if not is_training and iscrowd:
  235. continue
  236. if len(annos) >= 1:
  237. images.append(img_id)
  238. image_path_dict[img_id] = image_path
  239. image_anno_dict[img_id] = np.array(annos)
  240. return images, image_path_dict, image_anno_dict
  241. def anno_parser(annos_str):
  242. """Parse annotation from string to list."""
  243. annos = []
  244. for anno_str in annos_str:
  245. anno = list(map(int, anno_str.strip().split(',')))
  246. annos.append(anno)
  247. return annos
  248. def filter_valid_data(image_dir, anno_path):
  249. """Filter valid image file, which both in image_dir and anno_path."""
  250. images = []
  251. image_path_dict = {}
  252. image_anno_dict = {}
  253. if not os.path.isdir(image_dir):
  254. raise RuntimeError("Path given is not valid.")
  255. if not os.path.isfile(anno_path):
  256. raise RuntimeError("Annotation file is not valid.")
  257. with open(anno_path, "rb") as f:
  258. lines = f.readlines()
  259. for img_id, line in enumerate(lines):
  260. line_str = line.decode("utf-8").strip()
  261. line_split = str(line_str).split(' ')
  262. file_name = line_split[0]
  263. image_path = os.path.join(image_dir, file_name)
  264. if os.path.isfile(image_path):
  265. images.append(img_id)
  266. image_path_dict[img_id] = image_path
  267. image_anno_dict[img_id] = anno_parser(line_split[1:])
  268. return images, image_path_dict, image_anno_dict
  269. def voc_data_to_mindrecord(mindrecord_dir, is_training, prefix="retinanet.mindrecord", file_num=8):
  270. """Create MindRecord file by image_dir and anno_path."""
  271. mindrecord_path = os.path.join(mindrecord_dir, prefix)
  272. writer = FileWriter(mindrecord_path, file_num)
  273. images, image_path_dict, image_anno_dict = create_voc_label(is_training)
  274. retinanet_json = {
  275. "img_id": {"type": "int32", "shape": [1]},
  276. "image": {"type": "bytes"},
  277. "annotation": {"type": "int32", "shape": [-1, 5]},
  278. }
  279. writer.add_schema(retinanet_json, "retinanet_json")
  280. for img_id in images:
  281. image_path = image_path_dict[img_id]
  282. with open(image_path, 'rb') as f:
  283. img = f.read()
  284. annos = np.array(image_anno_dict[img_id], dtype=np.int32)
  285. img_id = np.array([img_id], dtype=np.int32)
  286. row = {"img_id": img_id, "image": img, "annotation": annos}
  287. writer.write_raw_data([row])
  288. writer.commit()
  289. def data_to_mindrecord_byte_image(dataset="coco", is_training=True, prefix="retinanet.mindrecord", file_num=8):
  290. """Create MindRecord file."""
  291. mindrecord_dir = config.mindrecord_dir
  292. mindrecord_path = os.path.join(mindrecord_dir, prefix)
  293. writer = FileWriter(mindrecord_path, file_num)
  294. if dataset == "coco":
  295. images, image_path_dict, image_anno_dict = create_coco_label(is_training)
  296. else:
  297. images, image_path_dict, image_anno_dict = filter_valid_data(config.image_dir, config.anno_path)
  298. retinanet_json = {
  299. "img_id": {"type": "int32", "shape": [1]},
  300. "image": {"type": "bytes"},
  301. "annotation": {"type": "int32", "shape": [-1, 5]},
  302. }
  303. writer.add_schema(retinanet_json, "retinanet_json")
  304. for img_id in images:
  305. image_path = image_path_dict[img_id]
  306. with open(image_path, 'rb') as f:
  307. img = f.read()
  308. annos = np.array(image_anno_dict[img_id], dtype=np.int32)
  309. img_id = np.array([img_id], dtype=np.int32)
  310. row = {"img_id": img_id, "image": img, "annotation": annos}
  311. writer.write_raw_data([row])
  312. writer.commit()
  313. def create_retinanet_dataset(mindrecord_file, batch_size, repeat_num, device_num=1, rank=0,
  314. is_training=True, num_parallel_workers=64):
  315. """Creatr retinanet dataset with MindDataset."""
  316. ds = de.MindDataset(mindrecord_file, columns_list=["img_id", "image", "annotation"], num_shards=device_num,
  317. shard_id=rank, num_parallel_workers=num_parallel_workers, shuffle=is_training)
  318. decode = C.Decode()
  319. ds = ds.map(operations=decode, input_columns=["image"])
  320. change_swap_op = C.HWC2CHW()
  321. normalize_op = C.Normalize(mean=[0.485 * 255, 0.456 * 255, 0.406 * 255],
  322. 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(operations=compose_map_func, input_columns=["img_id", "image", "annotation"],
  332. output_columns=output_columns, column_order=output_columns,
  333. python_multiprocessing=is_training,
  334. num_parallel_workers=num_parallel_workers)
  335. ds = ds.map(operations=trans, input_columns=["image"], 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
  340. def create_mindrecord(dataset="coco", prefix="retinanet.mindrecord", is_training=True):
  341. print("Start create dataset!")
  342. # It will generate mindrecord file in config.mindrecord_dir,
  343. # and the file name is retinanet.mindrecord0, 1, ... file_num.
  344. mindrecord_dir = config.mindrecord_dir
  345. mindrecord_file = os.path.join(mindrecord_dir, prefix + "0")
  346. if not os.path.exists(mindrecord_file):
  347. if not os.path.isdir(mindrecord_dir):
  348. os.makedirs(mindrecord_dir)
  349. if dataset == "coco":
  350. if os.path.isdir(config.coco_root):
  351. print("Create Mindrecord.")
  352. data_to_mindrecord_byte_image("coco", is_training, prefix)
  353. print("Create Mindrecord Done, at {}".format(mindrecord_dir))
  354. else:
  355. print("coco_root not exits.")
  356. elif dataset == "voc":
  357. if os.path.isdir(config.voc_dir):
  358. print("Create Mindrecord.")
  359. voc_data_to_mindrecord(mindrecord_dir, is_training, prefix)
  360. print("Create Mindrecord Done, at {}".format(mindrecord_dir))
  361. else:
  362. print("voc_dir not exits.")
  363. else:
  364. if os.path.isdir(config.image_dir) and os.path.exists(config.anno_path):
  365. print("Create Mindrecord.")
  366. data_to_mindrecord_byte_image("other", is_training, prefix)
  367. print("Create Mindrecord Done, at {}".format(mindrecord_dir))
  368. else:
  369. print("image_dir or anno_path not exits.")
  370. return mindrecord_file