You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1059 lines
42 KiB

  1. # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
  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. """A set of functions that are used for visualization.
  16. These functions often receive an image, perform some visualization on the image.
  17. The functions do not return a value, instead they modify the image itself.
  18. """
  19. import abc
  20. import collections
  21. # Set headless-friendly backend.
  22. import matplotlib; matplotlib.use('Agg') # pylint: disable=multiple-statements
  23. import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top
  24. import numpy as np
  25. import PIL.Image as Image
  26. import PIL.ImageColor as ImageColor
  27. import PIL.ImageDraw as ImageDraw
  28. import PIL.ImageFont as ImageFont
  29. import six
  30. import tensorflow as tf
  31. from object_detection.core import standard_fields as fields
  32. from object_detection.utils import shape_utils
  33. _TITLE_LEFT_MARGIN = 10
  34. _TITLE_TOP_MARGIN = 10
  35. STANDARD_COLORS = [
  36. 'AliceBlue', 'Chartreuse', 'Aqua', 'Aquamarine', 'Azure', 'Beige', 'Bisque',
  37. 'BlanchedAlmond', 'BlueViolet', 'BurlyWood', 'CadetBlue', 'AntiqueWhite',
  38. 'Chocolate', 'Coral', 'CornflowerBlue', 'Cornsilk', 'Crimson', 'Cyan',
  39. 'DarkCyan', 'DarkGoldenRod', 'DarkGrey', 'DarkKhaki', 'DarkOrange',
  40. 'DarkOrchid', 'DarkSalmon', 'DarkSeaGreen', 'DarkTurquoise', 'DarkViolet',
  41. 'DeepPink', 'DeepSkyBlue', 'DodgerBlue', 'FireBrick', 'FloralWhite',
  42. 'ForestGreen', 'Fuchsia', 'Gainsboro', 'GhostWhite', 'Gold', 'GoldenRod',
  43. 'Salmon', 'Tan', 'HoneyDew', 'HotPink', 'IndianRed', 'Ivory', 'Khaki',
  44. 'Lavender', 'LavenderBlush', 'LawnGreen', 'LemonChiffon', 'LightBlue',
  45. 'LightCoral', 'LightCyan', 'LightGoldenRodYellow', 'LightGray', 'LightGrey',
  46. 'LightGreen', 'LightPink', 'LightSalmon', 'LightSeaGreen', 'LightSkyBlue',
  47. 'LightSlateGray', 'LightSlateGrey', 'LightSteelBlue', 'LightYellow', 'Lime',
  48. 'LimeGreen', 'Linen', 'Magenta', 'MediumAquaMarine', 'MediumOrchid',
  49. 'MediumPurple', 'MediumSeaGreen', 'MediumSlateBlue', 'MediumSpringGreen',
  50. 'MediumTurquoise', 'MediumVioletRed', 'MintCream', 'MistyRose', 'Moccasin',
  51. 'NavajoWhite', 'OldLace', 'Olive', 'OliveDrab', 'Orange', 'OrangeRed',
  52. 'Orchid', 'PaleGoldenRod', 'PaleGreen', 'PaleTurquoise', 'PaleVioletRed',
  53. 'PapayaWhip', 'PeachPuff', 'Peru', 'Pink', 'Plum', 'PowderBlue', 'Purple',
  54. 'Red', 'RosyBrown', 'RoyalBlue', 'SaddleBrown', 'Green', 'SandyBrown',
  55. 'SeaGreen', 'SeaShell', 'Sienna', 'Silver', 'SkyBlue', 'SlateBlue',
  56. 'SlateGray', 'SlateGrey', 'Snow', 'SpringGreen', 'SteelBlue', 'GreenYellow',
  57. 'Teal', 'Thistle', 'Tomato', 'Turquoise', 'Violet', 'Wheat', 'White',
  58. 'WhiteSmoke', 'Yellow', 'YellowGreen'
  59. ]
  60. def _get_multiplier_for_color_randomness():
  61. """Returns a multiplier to get semi-random colors from successive indices.
  62. This function computes a prime number, p, in the range [2, 17] that:
  63. - is closest to len(STANDARD_COLORS) / 10
  64. - does not divide len(STANDARD_COLORS)
  65. If no prime numbers in that range satisfy the constraints, p is returned as 1.
  66. Once p is established, it can be used as a multiplier to select
  67. non-consecutive colors from STANDARD_COLORS:
  68. colors = [(p * i) % len(STANDARD_COLORS) for i in range(20)]
  69. """
  70. num_colors = len(STANDARD_COLORS)
  71. prime_candidates = [5, 7, 11, 13, 17]
  72. # Remove all prime candidates that divide the number of colors.
  73. prime_candidates = [p for p in prime_candidates if num_colors % p]
  74. if not prime_candidates:
  75. return 1
  76. # Return the closest prime number to num_colors / 10.
  77. abs_distance = [np.abs(num_colors / 10. - p) for p in prime_candidates]
  78. num_candidates = len(abs_distance)
  79. inds = [i for _, i in sorted(zip(abs_distance, range(num_candidates)))]
  80. return prime_candidates[inds[0]]
  81. def save_image_array_as_png(image, output_path):
  82. """Saves an image (represented as a numpy array) to PNG.
  83. Args:
  84. image: a numpy array with shape [height, width, 3].
  85. output_path: path to which image should be written.
  86. """
  87. image_pil = Image.fromarray(np.uint8(image)).convert('RGB')
  88. with tf.gfile.Open(output_path, 'w') as fid:
  89. image_pil.save(fid, 'PNG')
  90. def encode_image_array_as_png_str(image):
  91. """Encodes a numpy array into a PNG string.
  92. Args:
  93. image: a numpy array with shape [height, width, 3].
  94. Returns:
  95. PNG encoded image string.
  96. """
  97. image_pil = Image.fromarray(np.uint8(image))
  98. output = six.BytesIO()
  99. image_pil.save(output, format='PNG')
  100. png_string = output.getvalue()
  101. output.close()
  102. return png_string
  103. def draw_bounding_box_on_image_array(image,
  104. ymin,
  105. xmin,
  106. ymax,
  107. xmax,
  108. color='red',
  109. thickness=4,
  110. display_str_list=(),
  111. use_normalized_coordinates=True):
  112. """Adds a bounding box to an image (numpy array).
  113. Bounding box coordinates can be specified in either absolute (pixel) or
  114. normalized coordinates by setting the use_normalized_coordinates argument.
  115. Args:
  116. image: a numpy array with shape [height, width, 3].
  117. ymin: ymin of bounding box.
  118. xmin: xmin of bounding box.
  119. ymax: ymax of bounding box.
  120. xmax: xmax of bounding box.
  121. color: color to draw bounding box. Default is red.
  122. thickness: line thickness. Default value is 4.
  123. display_str_list: list of strings to display in box
  124. (each to be shown on its own line).
  125. use_normalized_coordinates: If True (default), treat coordinates
  126. ymin, xmin, ymax, xmax as relative to the image. Otherwise treat
  127. coordinates as absolute.
  128. """
  129. image_pil = Image.fromarray(np.uint8(image)).convert('RGB')
  130. draw_bounding_box_on_image(image_pil, ymin, xmin, ymax, xmax, color,
  131. thickness, display_str_list,
  132. use_normalized_coordinates)
  133. np.copyto(image, np.array(image_pil))
  134. def draw_bounding_box_on_image(image,
  135. ymin,
  136. xmin,
  137. ymax,
  138. xmax,
  139. color='red',
  140. thickness=4,
  141. display_str_list=(),
  142. use_normalized_coordinates=True):
  143. """Adds a bounding box to an image.
  144. Bounding box coordinates can be specified in either absolute (pixel) or
  145. normalized coordinates by setting the use_normalized_coordinates argument.
  146. Each string in display_str_list is displayed on a separate line above the
  147. bounding box in black text on a rectangle filled with the input 'color'.
  148. If the top of the bounding box extends to the edge of the image, the strings
  149. are displayed below the bounding box.
  150. Args:
  151. image: a PIL.Image object.
  152. ymin: ymin of bounding box.
  153. xmin: xmin of bounding box.
  154. ymax: ymax of bounding box.
  155. xmax: xmax of bounding box.
  156. color: color to draw bounding box. Default is red.
  157. thickness: line thickness. Default value is 4.
  158. display_str_list: list of strings to display in box
  159. (each to be shown on its own line).
  160. use_normalized_coordinates: If True (default), treat coordinates
  161. ymin, xmin, ymax, xmax as relative to the image. Otherwise treat
  162. coordinates as absolute.
  163. """
  164. draw = ImageDraw.Draw(image)
  165. im_width, im_height = image.size
  166. if use_normalized_coordinates:
  167. (left, right, top, bottom) = (xmin * im_width, xmax * im_width,
  168. ymin * im_height, ymax * im_height)
  169. else:
  170. (left, right, top, bottom) = (xmin, xmax, ymin, ymax)
  171. draw.line([(left, top), (left, bottom), (right, bottom),
  172. (right, top), (left, top)], width=thickness, fill=color)
  173. try:
  174. font = ImageFont.truetype('arial.ttf', 24)
  175. except IOError:
  176. font = ImageFont.load_default()
  177. # If the total height of the display strings added to the top of the bounding
  178. # box exceeds the top of the image, stack the strings below the bounding box
  179. # instead of above.
  180. display_str_heights = [font.getsize(ds)[1] for ds in display_str_list]
  181. # Each display_str has a top and bottom margin of 0.05x.
  182. total_display_str_height = (1 + 2 * 0.05) * sum(display_str_heights)
  183. if top > total_display_str_height:
  184. text_bottom = top
  185. else:
  186. text_bottom = bottom + total_display_str_height
  187. # Reverse list and print from bottom to top.
  188. for display_str in display_str_list[::-1]:
  189. text_width, text_height = font.getsize(display_str)
  190. margin = np.ceil(0.05 * text_height)
  191. draw.rectangle(
  192. [(left, text_bottom - text_height - 2 * margin), (left + text_width,
  193. text_bottom)],
  194. fill=color)
  195. draw.text(
  196. (left + margin, text_bottom - text_height - margin),
  197. display_str,
  198. fill='black',
  199. font=font)
  200. text_bottom -= text_height - 2 * margin
  201. def draw_bounding_boxes_on_image_array(image,
  202. boxes,
  203. color='red',
  204. thickness=4,
  205. display_str_list_list=()):
  206. """Draws bounding boxes on image (numpy array).
  207. Args:
  208. image: a numpy array object.
  209. boxes: a 2 dimensional numpy array of [N, 4]: (ymin, xmin, ymax, xmax).
  210. The coordinates are in normalized format between [0, 1].
  211. color: color to draw bounding box. Default is red.
  212. thickness: line thickness. Default value is 4.
  213. display_str_list_list: list of list of strings.
  214. a list of strings for each bounding box.
  215. The reason to pass a list of strings for a
  216. bounding box is that it might contain
  217. multiple labels.
  218. Raises:
  219. ValueError: if boxes is not a [N, 4] array
  220. """
  221. image_pil = Image.fromarray(image)
  222. draw_bounding_boxes_on_image(image_pil, boxes, color, thickness,
  223. display_str_list_list)
  224. np.copyto(image, np.array(image_pil))
  225. def draw_bounding_boxes_on_image(image,
  226. boxes,
  227. color='red',
  228. thickness=4,
  229. display_str_list_list=()):
  230. """Draws bounding boxes on image.
  231. Args:
  232. image: a PIL.Image object.
  233. boxes: a 2 dimensional numpy array of [N, 4]: (ymin, xmin, ymax, xmax).
  234. The coordinates are in normalized format between [0, 1].
  235. color: color to draw bounding box. Default is red.
  236. thickness: line thickness. Default value is 4.
  237. display_str_list_list: list of list of strings.
  238. a list of strings for each bounding box.
  239. The reason to pass a list of strings for a
  240. bounding box is that it might contain
  241. multiple labels.
  242. Raises:
  243. ValueError: if boxes is not a [N, 4] array
  244. """
  245. boxes_shape = boxes.shape
  246. if not boxes_shape:
  247. return
  248. if len(boxes_shape) != 2 or boxes_shape[1] != 4:
  249. raise ValueError('Input must be of size [N, 4]')
  250. for i in range(boxes_shape[0]):
  251. display_str_list = ()
  252. if display_str_list_list:
  253. display_str_list = display_str_list_list[i]
  254. draw_bounding_box_on_image(image, boxes[i, 0], boxes[i, 1], boxes[i, 2],
  255. boxes[i, 3], color, thickness, display_str_list)
  256. def create_visualization_fn(category_index, include_masks=False,
  257. include_keypoints=False, include_track_ids=False,
  258. **kwargs):
  259. """Constructs a visualization function that can be wrapped in a py_func.
  260. py_funcs only accept positional arguments. This function returns a suitable
  261. function with the correct positional argument mapping. The positional
  262. arguments in order are:
  263. 0: image
  264. 1: boxes
  265. 2: classes
  266. 3: scores
  267. [4-6]: masks (optional)
  268. [4-6]: keypoints (optional)
  269. [4-6]: track_ids (optional)
  270. -- Example 1 --
  271. vis_only_masks_fn = create_visualization_fn(category_index,
  272. include_masks=True, include_keypoints=False, include_track_ids=False,
  273. **kwargs)
  274. image = tf.py_func(vis_only_masks_fn,
  275. inp=[image, boxes, classes, scores, masks],
  276. Tout=tf.uint8)
  277. -- Example 2 --
  278. vis_masks_and_track_ids_fn = create_visualization_fn(category_index,
  279. include_masks=True, include_keypoints=False, include_track_ids=True,
  280. **kwargs)
  281. image = tf.py_func(vis_masks_and_track_ids_fn,
  282. inp=[image, boxes, classes, scores, masks, track_ids],
  283. Tout=tf.uint8)
  284. Args:
  285. category_index: a dict that maps integer ids to category dicts. e.g.
  286. {1: {1: 'dog'}, 2: {2: 'cat'}, ...}
  287. include_masks: Whether masks should be expected as a positional argument in
  288. the returned function.
  289. include_keypoints: Whether keypoints should be expected as a positional
  290. argument in the returned function.
  291. include_track_ids: Whether track ids should be expected as a positional
  292. argument in the returned function.
  293. **kwargs: Additional kwargs that will be passed to
  294. visualize_boxes_and_labels_on_image_array.
  295. Returns:
  296. Returns a function that only takes tensors as positional arguments.
  297. """
  298. def visualization_py_func_fn(*args):
  299. """Visualization function that can be wrapped in a tf.py_func.
  300. Args:
  301. *args: First 4 positional arguments must be:
  302. image - uint8 numpy array with shape (img_height, img_width, 3).
  303. boxes - a numpy array of shape [N, 4].
  304. classes - a numpy array of shape [N].
  305. scores - a numpy array of shape [N] or None.
  306. -- Optional positional arguments --
  307. instance_masks - a numpy array of shape [N, image_height, image_width].
  308. keypoints - a numpy array of shape [N, num_keypoints, 2].
  309. track_ids - a numpy array of shape [N] with unique track ids.
  310. Returns:
  311. uint8 numpy array with shape (img_height, img_width, 3) with overlaid
  312. boxes.
  313. """
  314. image = args[0]
  315. boxes = args[1]
  316. classes = args[2]
  317. scores = args[3]
  318. masks = keypoints = track_ids = None
  319. pos_arg_ptr = 4 # Positional argument for first optional tensor (masks).
  320. if include_masks:
  321. masks = args[pos_arg_ptr]
  322. pos_arg_ptr += 1
  323. if include_keypoints:
  324. keypoints = args[pos_arg_ptr]
  325. pos_arg_ptr += 1
  326. if include_track_ids:
  327. track_ids = args[pos_arg_ptr]
  328. return visualize_boxes_and_labels_on_image_array(
  329. image,
  330. boxes,
  331. classes,
  332. scores,
  333. category_index=category_index,
  334. instance_masks=masks,
  335. keypoints=keypoints,
  336. track_ids=track_ids,
  337. **kwargs)
  338. return visualization_py_func_fn
  339. def _resize_original_image(image, image_shape):
  340. image = tf.expand_dims(image, 0)
  341. image = tf.image.resize_images(
  342. image,
  343. image_shape,
  344. method=tf.image.ResizeMethod.NEAREST_NEIGHBOR,
  345. align_corners=True)
  346. return tf.cast(tf.squeeze(image, 0), tf.uint8)
  347. def draw_bounding_boxes_on_image_tensors(images,
  348. boxes,
  349. classes,
  350. scores,
  351. category_index,
  352. original_image_spatial_shape=None,
  353. true_image_shape=None,
  354. instance_masks=None,
  355. keypoints=None,
  356. track_ids=None,
  357. max_boxes_to_draw=20,
  358. min_score_thresh=0.2,
  359. use_normalized_coordinates=True):
  360. """Draws bounding boxes, masks, and keypoints on batch of image tensors.
  361. Args:
  362. images: A 4D uint8 image tensor of shape [N, H, W, C]. If C > 3, additional
  363. channels will be ignored. If C = 1, then we convert the images to RGB
  364. images.
  365. boxes: [N, max_detections, 4] float32 tensor of detection boxes.
  366. classes: [N, max_detections] int tensor of detection classes. Note that
  367. classes are 1-indexed.
  368. scores: [N, max_detections] float32 tensor of detection scores.
  369. category_index: a dict that maps integer ids to category dicts. e.g.
  370. {1: {1: 'dog'}, 2: {2: 'cat'}, ...}
  371. original_image_spatial_shape: [N, 2] tensor containing the spatial size of
  372. the original image.
  373. true_image_shape: [N, 3] tensor containing the spatial size of unpadded
  374. original_image.
  375. instance_masks: A 4D uint8 tensor of shape [N, max_detection, H, W] with
  376. instance masks.
  377. keypoints: A 4D float32 tensor of shape [N, max_detection, num_keypoints, 2]
  378. with keypoints.
  379. track_ids: [N, max_detections] int32 tensor of unique tracks ids (i.e.
  380. instance ids for each object). If provided, the color-coding of boxes is
  381. dictated by these ids, and not classes.
  382. max_boxes_to_draw: Maximum number of boxes to draw on an image. Default 20.
  383. min_score_thresh: Minimum score threshold for visualization. Default 0.2.
  384. use_normalized_coordinates: Whether to assume boxes and kepoints are in
  385. normalized coordinates (as opposed to absolute coordiantes).
  386. Default is True.
  387. Returns:
  388. 4D image tensor of type uint8, with boxes drawn on top.
  389. """
  390. # Additional channels are being ignored.
  391. if images.shape[3] > 3:
  392. images = images[:, :, :, 0:3]
  393. elif images.shape[3] == 1:
  394. images = tf.image.grayscale_to_rgb(images)
  395. visualization_keyword_args = {
  396. 'use_normalized_coordinates': use_normalized_coordinates,
  397. 'max_boxes_to_draw': max_boxes_to_draw,
  398. 'min_score_thresh': min_score_thresh,
  399. 'agnostic_mode': False,
  400. 'line_thickness': 4
  401. }
  402. if true_image_shape is None:
  403. true_shapes = tf.constant(-1, shape=[images.shape.as_list()[0], 3])
  404. else:
  405. true_shapes = true_image_shape
  406. if original_image_spatial_shape is None:
  407. original_shapes = tf.constant(-1, shape=[images.shape.as_list()[0], 2])
  408. else:
  409. original_shapes = original_image_spatial_shape
  410. visualize_boxes_fn = create_visualization_fn(
  411. category_index,
  412. include_masks=instance_masks is not None,
  413. include_keypoints=keypoints is not None,
  414. include_track_ids=track_ids is not None,
  415. **visualization_keyword_args)
  416. elems = [true_shapes, original_shapes, images, boxes, classes, scores]
  417. if instance_masks is not None:
  418. elems.append(instance_masks)
  419. if keypoints is not None:
  420. elems.append(keypoints)
  421. if track_ids is not None:
  422. elems.append(track_ids)
  423. def draw_boxes(image_and_detections):
  424. """Draws boxes on image."""
  425. true_shape = image_and_detections[0]
  426. original_shape = image_and_detections[1]
  427. if true_image_shape is not None:
  428. image = shape_utils.pad_or_clip_nd(image_and_detections[2],
  429. [true_shape[0], true_shape[1], 3])
  430. if original_image_spatial_shape is not None:
  431. image_and_detections[2] = _resize_original_image(image, original_shape)
  432. image_with_boxes = tf.py_func(visualize_boxes_fn, image_and_detections[2:],
  433. tf.uint8)
  434. return image_with_boxes
  435. images = tf.map_fn(draw_boxes, elems, dtype=tf.uint8, back_prop=False)
  436. return images
  437. def draw_side_by_side_evaluation_image(eval_dict,
  438. category_index,
  439. max_boxes_to_draw=20,
  440. min_score_thresh=0.2,
  441. use_normalized_coordinates=True):
  442. """Creates a side-by-side image with detections and groundtruth.
  443. Bounding boxes (and instance masks, if available) are visualized on both
  444. subimages.
  445. Args:
  446. eval_dict: The evaluation dictionary returned by
  447. eval_util.result_dict_for_batched_example() or
  448. eval_util.result_dict_for_single_example().
  449. category_index: A category index (dictionary) produced from a labelmap.
  450. max_boxes_to_draw: The maximum number of boxes to draw for detections.
  451. min_score_thresh: The minimum score threshold for showing detections.
  452. use_normalized_coordinates: Whether to assume boxes and kepoints are in
  453. normalized coordinates (as opposed to absolute coordiantes).
  454. Default is True.
  455. Returns:
  456. A list of [1, H, 2 * W, C] uint8 tensor. The subimage on the left
  457. corresponds to detections, while the subimage on the right corresponds to
  458. groundtruth.
  459. """
  460. detection_fields = fields.DetectionResultFields()
  461. input_data_fields = fields.InputDataFields()
  462. images_with_detections_list = []
  463. # Add the batch dimension if the eval_dict is for single example.
  464. if len(eval_dict[detection_fields.detection_classes].shape) == 1:
  465. for key in eval_dict:
  466. if key != input_data_fields.original_image:
  467. eval_dict[key] = tf.expand_dims(eval_dict[key], 0)
  468. for indx in range(eval_dict[input_data_fields.original_image].shape[0]):
  469. instance_masks = None
  470. if detection_fields.detection_masks in eval_dict:
  471. instance_masks = tf.cast(
  472. tf.expand_dims(
  473. eval_dict[detection_fields.detection_masks][indx], axis=0),
  474. tf.uint8)
  475. keypoints = None
  476. if detection_fields.detection_keypoints in eval_dict:
  477. keypoints = tf.expand_dims(
  478. eval_dict[detection_fields.detection_keypoints][indx], axis=0)
  479. groundtruth_instance_masks = None
  480. if input_data_fields.groundtruth_instance_masks in eval_dict:
  481. groundtruth_instance_masks = tf.cast(
  482. tf.expand_dims(
  483. eval_dict[input_data_fields.groundtruth_instance_masks][indx],
  484. axis=0), tf.uint8)
  485. images_with_detections = draw_bounding_boxes_on_image_tensors(
  486. tf.expand_dims(
  487. eval_dict[input_data_fields.original_image][indx], axis=0),
  488. tf.expand_dims(
  489. eval_dict[detection_fields.detection_boxes][indx], axis=0),
  490. tf.expand_dims(
  491. eval_dict[detection_fields.detection_classes][indx], axis=0),
  492. tf.expand_dims(
  493. eval_dict[detection_fields.detection_scores][indx], axis=0),
  494. category_index,
  495. original_image_spatial_shape=tf.expand_dims(
  496. eval_dict[input_data_fields.original_image_spatial_shape][indx],
  497. axis=0),
  498. true_image_shape=tf.expand_dims(
  499. eval_dict[input_data_fields.true_image_shape][indx], axis=0),
  500. instance_masks=instance_masks,
  501. keypoints=keypoints,
  502. max_boxes_to_draw=max_boxes_to_draw,
  503. min_score_thresh=min_score_thresh,
  504. use_normalized_coordinates=use_normalized_coordinates)
  505. images_with_groundtruth = draw_bounding_boxes_on_image_tensors(
  506. tf.expand_dims(
  507. eval_dict[input_data_fields.original_image][indx], axis=0),
  508. tf.expand_dims(
  509. eval_dict[input_data_fields.groundtruth_boxes][indx], axis=0),
  510. tf.expand_dims(
  511. eval_dict[input_data_fields.groundtruth_classes][indx], axis=0),
  512. tf.expand_dims(
  513. tf.ones_like(
  514. eval_dict[input_data_fields.groundtruth_classes][indx],
  515. dtype=tf.float32),
  516. axis=0),
  517. category_index,
  518. original_image_spatial_shape=tf.expand_dims(
  519. eval_dict[input_data_fields.original_image_spatial_shape][indx],
  520. axis=0),
  521. true_image_shape=tf.expand_dims(
  522. eval_dict[input_data_fields.true_image_shape][indx], axis=0),
  523. instance_masks=groundtruth_instance_masks,
  524. keypoints=None,
  525. max_boxes_to_draw=None,
  526. min_score_thresh=0.0,
  527. use_normalized_coordinates=use_normalized_coordinates)
  528. images_with_detections_list.append(
  529. tf.concat([images_with_detections, images_with_groundtruth], axis=2))
  530. return images_with_detections_list
  531. def draw_keypoints_on_image_array(image,
  532. keypoints,
  533. color='red',
  534. radius=2,
  535. use_normalized_coordinates=True):
  536. """Draws keypoints on an image (numpy array).
  537. Args:
  538. image: a numpy array with shape [height, width, 3].
  539. keypoints: a numpy array with shape [num_keypoints, 2].
  540. color: color to draw the keypoints with. Default is red.
  541. radius: keypoint radius. Default value is 2.
  542. use_normalized_coordinates: if True (default), treat keypoint values as
  543. relative to the image. Otherwise treat them as absolute.
  544. """
  545. image_pil = Image.fromarray(np.uint8(image)).convert('RGB')
  546. draw_keypoints_on_image(image_pil, keypoints, color, radius,
  547. use_normalized_coordinates)
  548. np.copyto(image, np.array(image_pil))
  549. def draw_keypoints_on_image(image,
  550. keypoints,
  551. color='red',
  552. radius=2,
  553. use_normalized_coordinates=True):
  554. """Draws keypoints on an image.
  555. Args:
  556. image: a PIL.Image object.
  557. keypoints: a numpy array with shape [num_keypoints, 2].
  558. color: color to draw the keypoints with. Default is red.
  559. radius: keypoint radius. Default value is 2.
  560. use_normalized_coordinates: if True (default), treat keypoint values as
  561. relative to the image. Otherwise treat them as absolute.
  562. """
  563. draw = ImageDraw.Draw(image)
  564. im_width, im_height = image.size
  565. keypoints_x = [k[1] for k in keypoints]
  566. keypoints_y = [k[0] for k in keypoints]
  567. if use_normalized_coordinates:
  568. keypoints_x = tuple([im_width * x for x in keypoints_x])
  569. keypoints_y = tuple([im_height * y for y in keypoints_y])
  570. for keypoint_x, keypoint_y in zip(keypoints_x, keypoints_y):
  571. draw.ellipse([(keypoint_x - radius, keypoint_y - radius),
  572. (keypoint_x + radius, keypoint_y + radius)],
  573. outline=color, fill=color)
  574. def draw_mask_on_image_array(image, mask, color='red', alpha=0.4):
  575. """Draws mask on an image.
  576. Args:
  577. image: uint8 numpy array with shape (img_height, img_height, 3)
  578. mask: a uint8 numpy array of shape (img_height, img_height) with
  579. values between either 0 or 1.
  580. color: color to draw the keypoints with. Default is red.
  581. alpha: transparency value between 0 and 1. (default: 0.4)
  582. Raises:
  583. ValueError: On incorrect data type for image or masks.
  584. """
  585. if image.dtype != np.uint8:
  586. raise ValueError('`image` not of type np.uint8')
  587. if mask.dtype != np.uint8:
  588. raise ValueError('`mask` not of type np.uint8')
  589. if np.any(np.logical_and(mask != 1, mask != 0)):
  590. raise ValueError('`mask` elements should be in [0, 1]')
  591. if image.shape[:2] != mask.shape:
  592. raise ValueError('The image has spatial dimensions %s but the mask has '
  593. 'dimensions %s' % (image.shape[:2], mask.shape))
  594. rgb = ImageColor.getrgb(color)
  595. pil_image = Image.fromarray(image)
  596. solid_color = np.expand_dims(
  597. np.ones_like(mask), axis=2) * np.reshape(list(rgb), [1, 1, 3])
  598. pil_solid_color = Image.fromarray(np.uint8(solid_color)).convert('RGBA')
  599. pil_mask = Image.fromarray(np.uint8(255.0*alpha*mask)).convert('L')
  600. pil_image = Image.composite(pil_solid_color, pil_image, pil_mask)
  601. np.copyto(image, np.array(pil_image.convert('RGB')))
  602. def visualize_boxes_and_labels_on_image_array(
  603. image,
  604. boxes,
  605. classes,
  606. scores,
  607. category_index,
  608. instance_masks=None,
  609. instance_boundaries=None,
  610. keypoints=None,
  611. track_ids=None,
  612. use_normalized_coordinates=False,
  613. max_boxes_to_draw=20,
  614. min_score_thresh=.5,
  615. agnostic_mode=False,
  616. line_thickness=4,
  617. groundtruth_box_visualization_color='black',
  618. skip_scores=False,
  619. skip_labels=False,
  620. skip_track_ids=False):
  621. """Overlay labeled boxes on an image with formatted scores and label names.
  622. This function groups boxes that correspond to the same location
  623. and creates a display string for each detection and overlays these
  624. on the image. Note that this function modifies the image in place, and returns
  625. that same image.
  626. Args:
  627. image: uint8 numpy array with shape (img_height, img_width, 3)
  628. boxes: a numpy array of shape [N, 4]
  629. classes: a numpy array of shape [N]. Note that class indices are 1-based,
  630. and match the keys in the label map.
  631. scores: a numpy array of shape [N] or None. If scores=None, then
  632. this function assumes that the boxes to be plotted are groundtruth
  633. boxes and plot all boxes as black with no classes or scores.
  634. category_index: a dict containing category dictionaries (each holding
  635. category index `id` and category name `name`) keyed by category indices.
  636. instance_masks: a numpy array of shape [N, image_height, image_width] with
  637. values ranging between 0 and 1, can be None.
  638. instance_boundaries: a numpy array of shape [N, image_height, image_width]
  639. with values ranging between 0 and 1, can be None.
  640. keypoints: a numpy array of shape [N, num_keypoints, 2], can
  641. be None
  642. track_ids: a numpy array of shape [N] with unique track ids. If provided,
  643. color-coding of boxes will be determined by these ids, and not the class
  644. indices.
  645. use_normalized_coordinates: whether boxes is to be interpreted as
  646. normalized coordinates or not.
  647. max_boxes_to_draw: maximum number of boxes to visualize. If None, draw
  648. all boxes.
  649. min_score_thresh: minimum score threshold for a box to be visualized
  650. agnostic_mode: boolean (default: False) controlling whether to evaluate in
  651. class-agnostic mode or not. This mode will display scores but ignore
  652. classes.
  653. line_thickness: integer (default: 4) controlling line width of the boxes.
  654. groundtruth_box_visualization_color: box color for visualizing groundtruth
  655. boxes
  656. skip_scores: whether to skip score when drawing a single detection
  657. skip_labels: whether to skip label when drawing a single detection
  658. skip_track_ids: whether to skip track id when drawing a single detection
  659. Returns:
  660. uint8 numpy array with shape (img_height, img_width, 3) with overlaid boxes.
  661. """
  662. # Create a display string (and color) for every box location, group any boxes
  663. # that correspond to the same location.
  664. box_to_display_str_map = collections.defaultdict(list)
  665. box_to_color_map = collections.defaultdict(str)
  666. box_to_instance_masks_map = {}
  667. box_to_instance_boundaries_map = {}
  668. box_to_keypoints_map = collections.defaultdict(list)
  669. box_to_track_ids_map = {}
  670. if not max_boxes_to_draw:
  671. max_boxes_to_draw = boxes.shape[0]
  672. for i in range(min(max_boxes_to_draw, boxes.shape[0])):
  673. if scores is None or scores[i] > min_score_thresh:
  674. box = tuple(boxes[i].tolist())
  675. if instance_masks is not None:
  676. box_to_instance_masks_map[box] = instance_masks[i]
  677. if instance_boundaries is not None:
  678. box_to_instance_boundaries_map[box] = instance_boundaries[i]
  679. if keypoints is not None:
  680. box_to_keypoints_map[box].extend(keypoints[i])
  681. if track_ids is not None:
  682. box_to_track_ids_map[box] = track_ids[i]
  683. if scores is None:
  684. box_to_color_map[box] = groundtruth_box_visualization_color
  685. else:
  686. display_str = ''
  687. if not skip_labels:
  688. if not agnostic_mode:
  689. if classes[i] in category_index.keys():
  690. class_name = category_index[classes[i]]['name']
  691. else:
  692. class_name = 'N/A'
  693. display_str = str(class_name)
  694. if not skip_scores:
  695. if not display_str:
  696. display_str = '{}%'.format(int(100*scores[i]))
  697. else:
  698. display_str = '{}: {}%'.format(display_str, int(100*scores[i]))
  699. if not skip_track_ids and track_ids is not None:
  700. if not display_str:
  701. display_str = 'ID {}'.format(track_ids[i])
  702. else:
  703. display_str = '{}: ID {}'.format(display_str, track_ids[i])
  704. box_to_display_str_map[box].append(display_str)
  705. if agnostic_mode:
  706. box_to_color_map[box] = 'DarkOrange'
  707. elif track_ids is not None:
  708. prime_multipler = _get_multiplier_for_color_randomness()
  709. box_to_color_map[box] = STANDARD_COLORS[
  710. (prime_multipler * track_ids[i]) % len(STANDARD_COLORS)]
  711. else:
  712. box_to_color_map[box] = STANDARD_COLORS[
  713. classes[i] % len(STANDARD_COLORS)]
  714. # Draw all boxes onto image.
  715. for box, color in box_to_color_map.items():
  716. ymin, xmin, ymax, xmax = box
  717. if instance_masks is not None:
  718. draw_mask_on_image_array(
  719. image,
  720. box_to_instance_masks_map[box],
  721. color=color
  722. )
  723. if instance_boundaries is not None:
  724. draw_mask_on_image_array(
  725. image,
  726. box_to_instance_boundaries_map[box],
  727. color='red',
  728. alpha=1.0
  729. )
  730. draw_bounding_box_on_image_array(
  731. image,
  732. ymin,
  733. xmin,
  734. ymax,
  735. xmax,
  736. color=color,
  737. thickness=line_thickness,
  738. display_str_list=box_to_display_str_map[box],
  739. use_normalized_coordinates=use_normalized_coordinates)
  740. if keypoints is not None:
  741. draw_keypoints_on_image_array(
  742. image,
  743. box_to_keypoints_map[box],
  744. color=color,
  745. radius=line_thickness / 2,
  746. use_normalized_coordinates=use_normalized_coordinates)
  747. return image
  748. def add_cdf_image_summary(values, name):
  749. """Adds a tf.summary.image for a CDF plot of the values.
  750. Normalizes `values` such that they sum to 1, plots the cumulative distribution
  751. function and creates a tf image summary.
  752. Args:
  753. values: a 1-D float32 tensor containing the values.
  754. name: name for the image summary.
  755. """
  756. def cdf_plot(values):
  757. """Numpy function to plot CDF."""
  758. normalized_values = values / np.sum(values)
  759. sorted_values = np.sort(normalized_values)
  760. cumulative_values = np.cumsum(sorted_values)
  761. fraction_of_examples = (np.arange(cumulative_values.size, dtype=np.float32)
  762. / cumulative_values.size)
  763. fig = plt.figure(frameon=False)
  764. ax = fig.add_subplot('111')
  765. ax.plot(fraction_of_examples, cumulative_values)
  766. ax.set_ylabel('cumulative normalized values')
  767. ax.set_xlabel('fraction of examples')
  768. fig.canvas.draw()
  769. width, height = fig.get_size_inches() * fig.get_dpi()
  770. image = np.fromstring(fig.canvas.tostring_rgb(), dtype='uint8').reshape(
  771. 1, int(height), int(width), 3)
  772. return image
  773. cdf_plot = tf.py_func(cdf_plot, [values], tf.uint8)
  774. tf.summary.image(name, cdf_plot)
  775. def add_hist_image_summary(values, bins, name):
  776. """Adds a tf.summary.image for a histogram plot of the values.
  777. Plots the histogram of values and creates a tf image summary.
  778. Args:
  779. values: a 1-D float32 tensor containing the values.
  780. bins: bin edges which will be directly passed to np.histogram.
  781. name: name for the image summary.
  782. """
  783. def hist_plot(values, bins):
  784. """Numpy function to plot hist."""
  785. fig = plt.figure(frameon=False)
  786. ax = fig.add_subplot('111')
  787. y, x = np.histogram(values, bins=bins)
  788. ax.plot(x[:-1], y)
  789. ax.set_ylabel('count')
  790. ax.set_xlabel('value')
  791. fig.canvas.draw()
  792. width, height = fig.get_size_inches() * fig.get_dpi()
  793. image = np.fromstring(
  794. fig.canvas.tostring_rgb(), dtype='uint8').reshape(
  795. 1, int(height), int(width), 3)
  796. return image
  797. hist_plot = tf.py_func(hist_plot, [values, bins], tf.uint8)
  798. tf.summary.image(name, hist_plot)
  799. class EvalMetricOpsVisualization(object):
  800. """Abstract base class responsible for visualizations during evaluation.
  801. Currently, summary images are not run during evaluation. One way to produce
  802. evaluation images in Tensorboard is to provide tf.summary.image strings as
  803. `value_ops` in tf.estimator.EstimatorSpec's `eval_metric_ops`. This class is
  804. responsible for accruing images (with overlaid detections and groundtruth)
  805. and returning a dictionary that can be passed to `eval_metric_ops`.
  806. """
  807. __metaclass__ = abc.ABCMeta
  808. def __init__(self,
  809. category_index,
  810. max_examples_to_draw=5,
  811. max_boxes_to_draw=20,
  812. min_score_thresh=0.2,
  813. use_normalized_coordinates=True,
  814. summary_name_prefix='evaluation_image'):
  815. """Creates an EvalMetricOpsVisualization.
  816. Args:
  817. category_index: A category index (dictionary) produced from a labelmap.
  818. max_examples_to_draw: The maximum number of example summaries to produce.
  819. max_boxes_to_draw: The maximum number of boxes to draw for detections.
  820. min_score_thresh: The minimum score threshold for showing detections.
  821. use_normalized_coordinates: Whether to assume boxes and kepoints are in
  822. normalized coordinates (as opposed to absolute coordiantes).
  823. Default is True.
  824. summary_name_prefix: A string prefix for each image summary.
  825. """
  826. self._category_index = category_index
  827. self._max_examples_to_draw = max_examples_to_draw
  828. self._max_boxes_to_draw = max_boxes_to_draw
  829. self._min_score_thresh = min_score_thresh
  830. self._use_normalized_coordinates = use_normalized_coordinates
  831. self._summary_name_prefix = summary_name_prefix
  832. self._images = []
  833. def clear(self):
  834. self._images = []
  835. def add_images(self, images):
  836. """Store a list of images, each with shape [1, H, W, C]."""
  837. if len(self._images) >= self._max_examples_to_draw:
  838. return
  839. # Store images and clip list if necessary.
  840. self._images.extend(images)
  841. if len(self._images) > self._max_examples_to_draw:
  842. self._images[self._max_examples_to_draw:] = []
  843. def get_estimator_eval_metric_ops(self, eval_dict):
  844. """Returns metric ops for use in tf.estimator.EstimatorSpec.
  845. Args:
  846. eval_dict: A dictionary that holds an image, groundtruth, and detections
  847. for a batched example. Note that, we use only the first example for
  848. visualization. See eval_util.result_dict_for_batched_example() for a
  849. convenient method for constructing such a dictionary. The dictionary
  850. contains
  851. fields.InputDataFields.original_image: [batch_size, H, W, 3] image.
  852. fields.InputDataFields.original_image_spatial_shape: [batch_size, 2]
  853. tensor containing the size of the original image.
  854. fields.InputDataFields.true_image_shape: [batch_size, 3]
  855. tensor containing the spatial size of the upadded original image.
  856. fields.InputDataFields.groundtruth_boxes - [batch_size, num_boxes, 4]
  857. float32 tensor with groundtruth boxes in range [0.0, 1.0].
  858. fields.InputDataFields.groundtruth_classes - [batch_size, num_boxes]
  859. int64 tensor with 1-indexed groundtruth classes.
  860. fields.InputDataFields.groundtruth_instance_masks - (optional)
  861. [batch_size, num_boxes, H, W] int64 tensor with instance masks.
  862. fields.DetectionResultFields.detection_boxes - [batch_size,
  863. max_num_boxes, 4] float32 tensor with detection boxes in range [0.0,
  864. 1.0].
  865. fields.DetectionResultFields.detection_classes - [batch_size,
  866. max_num_boxes] int64 tensor with 1-indexed detection classes.
  867. fields.DetectionResultFields.detection_scores - [batch_size,
  868. max_num_boxes] float32 tensor with detection scores.
  869. fields.DetectionResultFields.detection_masks - (optional) [batch_size,
  870. max_num_boxes, H, W] float32 tensor of binarized masks.
  871. fields.DetectionResultFields.detection_keypoints - (optional)
  872. [batch_size, max_num_boxes, num_keypoints, 2] float32 tensor with
  873. keypoints.
  874. Returns:
  875. A dictionary of image summary names to tuple of (value_op, update_op). The
  876. `update_op` is the same for all items in the dictionary, and is
  877. responsible for saving a single side-by-side image with detections and
  878. groundtruth. Each `value_op` holds the tf.summary.image string for a given
  879. image.
  880. """
  881. if self._max_examples_to_draw == 0:
  882. return {}
  883. images = self.images_from_evaluation_dict(eval_dict)
  884. def get_images():
  885. """Returns a list of images, padded to self._max_images_to_draw."""
  886. images = self._images
  887. while len(images) < self._max_examples_to_draw:
  888. images.append(np.array(0, dtype=np.uint8))
  889. self.clear()
  890. return images
  891. def image_summary_or_default_string(summary_name, image):
  892. """Returns image summaries for non-padded elements."""
  893. return tf.cond(
  894. tf.equal(tf.size(tf.shape(image)), 4),
  895. lambda: tf.summary.image(summary_name, image),
  896. lambda: tf.constant(''))
  897. if tf.executing_eagerly():
  898. update_op = self.add_images([[images[0]]])
  899. image_tensors = get_images()
  900. else:
  901. update_op = tf.py_func(self.add_images, [[images[0]]], [])
  902. image_tensors = tf.py_func(
  903. get_images, [], [tf.uint8] * self._max_examples_to_draw)
  904. eval_metric_ops = {}
  905. for i, image in enumerate(image_tensors):
  906. summary_name = self._summary_name_prefix + '/' + str(i)
  907. value_op = image_summary_or_default_string(summary_name, image)
  908. eval_metric_ops[summary_name] = (value_op, update_op)
  909. return eval_metric_ops
  910. @abc.abstractmethod
  911. def images_from_evaluation_dict(self, eval_dict):
  912. """Converts evaluation dictionary into a list of image tensors.
  913. To be overridden by implementations.
  914. Args:
  915. eval_dict: A dictionary with all the necessary information for producing
  916. visualizations.
  917. Returns:
  918. A list of [1, H, W, C] uint8 tensors.
  919. """
  920. raise NotImplementedError
  921. class VisualizeSingleFrameDetections(EvalMetricOpsVisualization):
  922. """Class responsible for single-frame object detection visualizations."""
  923. def __init__(self,
  924. category_index,
  925. max_examples_to_draw=5,
  926. max_boxes_to_draw=20,
  927. min_score_thresh=0.2,
  928. use_normalized_coordinates=True,
  929. summary_name_prefix='Detections_Left_Groundtruth_Right'):
  930. super(VisualizeSingleFrameDetections, self).__init__(
  931. category_index=category_index,
  932. max_examples_to_draw=max_examples_to_draw,
  933. max_boxes_to_draw=max_boxes_to_draw,
  934. min_score_thresh=min_score_thresh,
  935. use_normalized_coordinates=use_normalized_coordinates,
  936. summary_name_prefix=summary_name_prefix)
  937. def images_from_evaluation_dict(self, eval_dict):
  938. return draw_side_by_side_evaluation_image(
  939. eval_dict, self._category_index, self._max_boxes_to_draw,
  940. self._min_score_thresh, self._use_normalized_coordinates)