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.

util.py 15 kB

5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. # Copyright 2019 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. import hashlib
  16. import json
  17. import os
  18. from enum import Enum
  19. import matplotlib.pyplot as plt
  20. import matplotlib.patches as patches
  21. import numpy as np
  22. # import jsbeautifier
  23. import mindspore.dataset as ds
  24. from mindspore import log as logger
  25. # These are list of plot title in different visualize modes
  26. PLOT_TITLE_DICT = {
  27. 1: ["Original image", "Transformed image"],
  28. 2: ["c_transform image", "py_transform image"]
  29. }
  30. SAVE_JSON = False
  31. def _save_golden(cur_dir, golden_ref_dir, result_dict):
  32. """
  33. Save the dictionary values as the golden result in .npz file
  34. """
  35. logger.info("cur_dir is {}".format(cur_dir))
  36. logger.info("golden_ref_dir is {}".format(golden_ref_dir))
  37. np.savez(golden_ref_dir, np.array(list(result_dict.values())))
  38. def _save_golden_dict(cur_dir, golden_ref_dir, result_dict):
  39. """
  40. Save the dictionary (both keys and values) as the golden result in .npz file
  41. """
  42. logger.info("cur_dir is {}".format(cur_dir))
  43. logger.info("golden_ref_dir is {}".format(golden_ref_dir))
  44. np.savez(golden_ref_dir, np.array(list(result_dict.items())))
  45. def _compare_to_golden(golden_ref_dir, result_dict):
  46. """
  47. Compare as numpy arrays the test result to the golden result
  48. """
  49. test_array = np.array(list(result_dict.values()))
  50. golden_array = np.load(golden_ref_dir, allow_pickle=True)['arr_0']
  51. np.testing.assert_array_equal(test_array, golden_array)
  52. def _compare_to_golden_dict(golden_ref_dir, result_dict):
  53. """
  54. Compare as dictionaries the test result to the golden result
  55. """
  56. golden_array = np.load(golden_ref_dir, allow_pickle=True)['arr_0']
  57. np.testing.assert_equal(result_dict, dict(golden_array))
  58. def _save_json(filename, parameters, result_dict):
  59. """
  60. Save the result dictionary in json file
  61. """
  62. fout = open(filename[:-3] + "json", "w")
  63. options = jsbeautifier.default_options()
  64. options.indent_size = 2
  65. out_dict = {**parameters, **{"columns": result_dict}}
  66. fout.write(jsbeautifier.beautify(json.dumps(out_dict), options))
  67. def save_and_check_dict(data, filename, generate_golden=False):
  68. """
  69. Save the dataset dictionary and compare (as dictionary) with golden file.
  70. Use create_dict_iterator to access the dataset.
  71. """
  72. num_iter = 0
  73. result_dict = {}
  74. for item in data.create_dict_iterator(): # each data is a dictionary
  75. for data_key in list(item.keys()):
  76. if data_key not in result_dict:
  77. result_dict[data_key] = []
  78. result_dict[data_key].append(item[data_key].tolist())
  79. num_iter += 1
  80. logger.info("Number of data in ds1: {}".format(num_iter))
  81. cur_dir = os.path.dirname(os.path.realpath(__file__))
  82. golden_ref_dir = os.path.join(cur_dir, "../../data/dataset", 'golden', filename)
  83. if generate_golden:
  84. # Save as the golden result
  85. _save_golden_dict(cur_dir, golden_ref_dir, result_dict)
  86. _compare_to_golden_dict(golden_ref_dir, result_dict)
  87. if SAVE_JSON:
  88. # Save result to a json file for inspection
  89. parameters = {"params": {}}
  90. _save_json(filename, parameters, result_dict)
  91. def save_and_check_md5(data, filename, generate_golden=False):
  92. """
  93. Save the dataset dictionary and compare (as dictionary) with golden file (md5).
  94. Use create_dict_iterator to access the dataset.
  95. """
  96. num_iter = 0
  97. result_dict = {}
  98. for item in data.create_dict_iterator(): # each data is a dictionary
  99. for data_key in list(item.keys()):
  100. if data_key not in result_dict:
  101. result_dict[data_key] = []
  102. # save the md5 as numpy array
  103. result_dict[data_key].append(np.frombuffer(hashlib.md5(item[data_key]).digest(), dtype='<f4'))
  104. num_iter += 1
  105. logger.info("Number of data in ds1: {}".format(num_iter))
  106. cur_dir = os.path.dirname(os.path.realpath(__file__))
  107. golden_ref_dir = os.path.join(cur_dir, "../../data/dataset", 'golden', filename)
  108. if generate_golden:
  109. # Save as the golden result
  110. _save_golden_dict(cur_dir, golden_ref_dir, result_dict)
  111. _compare_to_golden_dict(golden_ref_dir, result_dict)
  112. def save_and_check_tuple(data, parameters, filename, generate_golden=False):
  113. """
  114. Save the dataset dictionary and compare (as numpy array) with golden file.
  115. Use create_tuple_iterator to access the dataset.
  116. """
  117. num_iter = 0
  118. result_dict = {}
  119. for item in data.create_tuple_iterator(): # each data is a dictionary
  120. for data_key, _ in enumerate(item):
  121. if data_key not in result_dict:
  122. result_dict[data_key] = []
  123. result_dict[data_key].append(item[data_key].tolist())
  124. num_iter += 1
  125. logger.info("Number of data in data1: {}".format(num_iter))
  126. cur_dir = os.path.dirname(os.path.realpath(__file__))
  127. golden_ref_dir = os.path.join(cur_dir, "../../data/dataset", 'golden', filename)
  128. if generate_golden:
  129. # Save as the golden result
  130. _save_golden(cur_dir, golden_ref_dir, result_dict)
  131. _compare_to_golden(golden_ref_dir, result_dict)
  132. if SAVE_JSON:
  133. # Save result to a json file for inspection
  134. _save_json(filename, parameters, result_dict)
  135. def config_get_set_seed(seed_new):
  136. """
  137. Get and return the original configuration seed value.
  138. Set the new configuration seed value.
  139. """
  140. seed_original = ds.config.get_seed()
  141. ds.config.set_seed(seed_new)
  142. logger.info("seed: original = {} new = {} ".format(seed_original, seed_new))
  143. return seed_original
  144. def config_get_set_num_parallel_workers(num_parallel_workers_new):
  145. """
  146. Get and return the original configuration num_parallel_workers value.
  147. Set the new configuration num_parallel_workers value.
  148. """
  149. num_parallel_workers_original = ds.config.get_num_parallel_workers()
  150. ds.config.set_num_parallel_workers(num_parallel_workers_new)
  151. logger.info("num_parallel_workers: original = {} new = {} ".format(num_parallel_workers_original,
  152. num_parallel_workers_new))
  153. return num_parallel_workers_original
  154. def diff_mse(in1, in2):
  155. mse = (np.square(in1.astype(float) / 255 - in2.astype(float) / 255)).mean()
  156. return mse * 100
  157. def diff_me(in1, in2):
  158. mse = (np.abs(in1.astype(float) - in2.astype(float))).mean()
  159. return mse / 255 * 100
  160. def visualize_one_channel_dataset(images_original, images_transformed, labels):
  161. """
  162. Helper function to visualize one channel grayscale images
  163. """
  164. num_samples = len(images_original)
  165. for i in range(num_samples):
  166. plt.subplot(2, num_samples, i + 1)
  167. # Note: Use squeeze() to convert (H, W, 1) images to (H, W)
  168. plt.imshow(images_original[i].squeeze(), cmap=plt.cm.gray)
  169. plt.title(PLOT_TITLE_DICT[1][0] + ":" + str(labels[i]))
  170. plt.subplot(2, num_samples, i + num_samples + 1)
  171. plt.imshow(images_transformed[i].squeeze(), cmap=plt.cm.gray)
  172. plt.title(PLOT_TITLE_DICT[1][1] + ":" + str(labels[i]))
  173. plt.show()
  174. def visualize_list(image_list_1, image_list_2, visualize_mode=1):
  175. """
  176. visualizes a list of images using DE op
  177. """
  178. plot_title = PLOT_TITLE_DICT[visualize_mode]
  179. num = len(image_list_1)
  180. for i in range(num):
  181. plt.subplot(2, num, i + 1)
  182. plt.imshow(image_list_1[i])
  183. plt.title(plot_title[0])
  184. plt.subplot(2, num, i + num + 1)
  185. plt.imshow(image_list_2[i])
  186. plt.title(plot_title[1])
  187. plt.show()
  188. def visualize_image(image_original, image_de, mse=None, image_lib=None):
  189. """
  190. visualizes one example image with optional input: mse, image using 3rd party op.
  191. If three images are passing in, different image is calculated by 2nd and 3rd images.
  192. """
  193. num = 2
  194. if image_lib is not None:
  195. num += 1
  196. if mse is not None:
  197. num += 1
  198. plt.subplot(1, num, 1)
  199. plt.imshow(image_original)
  200. plt.title("Original image")
  201. plt.subplot(1, num, 2)
  202. plt.imshow(image_de)
  203. plt.title("DE Op image")
  204. if image_lib is not None:
  205. plt.subplot(1, num, 3)
  206. plt.imshow(image_lib)
  207. plt.title("Lib Op image")
  208. if mse is not None:
  209. plt.subplot(1, num, 4)
  210. plt.imshow(image_de - image_lib)
  211. plt.title("Diff image,\n mse : {}".format(mse))
  212. elif mse is not None:
  213. plt.subplot(1, num, 3)
  214. plt.imshow(image_original - image_de)
  215. plt.title("Diff image,\n mse : {}".format(mse))
  216. plt.show()
  217. def visualize_with_bounding_boxes(orig, aug, annot_name="bbox", plot_rows=3):
  218. """
  219. Take a list of un-augmented and augmented images with "bbox" bounding boxes
  220. Plot images to compare test correct BBox augment functionality
  221. :param orig: list of original images and bboxes (without aug)
  222. :param aug: list of augmented images and bboxes
  223. :param annot_name: the dict key for bboxes in data, e.g "bbox" (COCO) / "bbox" (VOC)
  224. :param plot_rows: number of rows on plot (rows = samples on one plot)
  225. :return: None
  226. """
  227. def add_bounding_boxes(ax, bboxes):
  228. for bbox in bboxes:
  229. rect = patches.Rectangle((bbox[0], bbox[1]),
  230. bbox[2]*0.997, bbox[3]*0.997,
  231. linewidth=1.80, edgecolor='r', facecolor='none')
  232. # Add the patch to the Axes
  233. # Params to Rectangle slightly modified to prevent drawing overflow
  234. ax.add_patch(rect)
  235. # Quick check to confirm correct input parameters
  236. if not isinstance(orig, list) or not isinstance(aug, list):
  237. return
  238. if len(orig) != len(aug) or not orig:
  239. return
  240. batch_size = int(len(orig) / plot_rows) # creates batches of images to plot together
  241. split_point = batch_size * plot_rows
  242. orig, aug = np.array(orig), np.array(aug)
  243. if len(orig) > plot_rows:
  244. # Create batches of required size and add remainder to last batch
  245. orig = np.split(orig[:split_point], batch_size) + (
  246. [orig[split_point:]] if (split_point < orig.shape[0]) else []) # check to avoid empty arrays being added
  247. aug = np.split(aug[:split_point], batch_size) + ([aug[split_point:]] if (split_point < aug.shape[0]) else [])
  248. else:
  249. orig = [orig]
  250. aug = [aug]
  251. for ix, allData in enumerate(zip(orig, aug)):
  252. base_ix = ix * plot_rows # current batch starting index
  253. curPlot = len(allData[0])
  254. fig, axs = plt.subplots(curPlot, 2)
  255. fig.tight_layout(pad=1.5)
  256. for x, (dataA, dataB) in enumerate(zip(allData[0], allData[1])):
  257. cur_ix = base_ix + x
  258. # select plotting axes based on number of image rows on plot - else case when 1 row
  259. (axA, axB) = (axs[x, 0], axs[x, 1]) if (curPlot > 1) else (axs[0], axs[1])
  260. axA.imshow(dataA["image"])
  261. add_bounding_boxes(axA, dataA[annot_name])
  262. axA.title.set_text("Original" + str(cur_ix+1))
  263. axB.imshow(dataB["image"])
  264. add_bounding_boxes(axB, dataB[annot_name])
  265. axB.title.set_text("Augmented" + str(cur_ix+1))
  266. logger.info("Original **\n{} : {}".format(str(cur_ix+1), dataA[annot_name]))
  267. logger.info("Augmented **\n{} : {}\n".format(str(cur_ix+1), dataB[annot_name]))
  268. plt.show()
  269. class InvalidBBoxType(Enum):
  270. """
  271. Defines Invalid Bounding Bbox types for test cases
  272. """
  273. WidthOverflow = 1
  274. HeightOverflow = 2
  275. NegativeXY = 3
  276. WrongShape = 4
  277. def check_bad_bbox(data, test_op, invalid_bbox_type, expected_error):
  278. """
  279. :param data: de object detection pipeline
  280. :param test_op: Augmentation Op to test on image
  281. :param invalid_bbox_type: type of bad box
  282. :param expected_error: error expected to get due to bad box
  283. :return: None
  284. """
  285. def add_bad_bbox(img, bboxes, invalid_bbox_type_):
  286. """
  287. Used to generate erroneous bounding box examples on given img.
  288. :param img: image where the bounding boxes are.
  289. :param bboxes: in [x_min, y_min, w, h, label, truncate, difficult] format
  290. :param box_type_: type of bad box
  291. :return: bboxes with bad examples added
  292. """
  293. height = img.shape[0]
  294. width = img.shape[1]
  295. if invalid_bbox_type_ == InvalidBBoxType.WidthOverflow:
  296. # use box that overflows on width
  297. return img, np.array([[0, 0, width + 1, height, 0, 0, 0]]).astype(np.float32)
  298. if invalid_bbox_type_ == InvalidBBoxType.HeightOverflow:
  299. # use box that overflows on height
  300. return img, np.array([[0, 0, width, height + 1, 0, 0, 0]]).astype(np.float32)
  301. if invalid_bbox_type_ == InvalidBBoxType.NegativeXY:
  302. # use box with negative xy
  303. return img, np.array([[-10, -10, width, height, 0, 0, 0]]).astype(np.float32)
  304. if invalid_bbox_type_ == InvalidBBoxType.WrongShape:
  305. # use box that has incorrect shape
  306. return img, np.array([[0, 0, width - 1]]).astype(np.float32)
  307. return img, bboxes
  308. try:
  309. # map to use selected invalid bounding box type
  310. data = data.map(input_columns=["image", "bbox"],
  311. output_columns=["image", "bbox"],
  312. columns_order=["image", "bbox"],
  313. operations=lambda img, bboxes: add_bad_bbox(img, bboxes, invalid_bbox_type))
  314. # map to apply ops
  315. data = data.map(input_columns=["image", "bbox"],
  316. output_columns=["image", "bbox"],
  317. columns_order=["image", "bbox"],
  318. operations=[test_op]) # Add column for "bbox"
  319. for _, _ in enumerate(data.create_dict_iterator()):
  320. break
  321. except RuntimeError as error:
  322. logger.info("Got an exception in DE: {}".format(str(error)))
  323. assert expected_error in str(error)