visualize.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. #copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  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. import os
  15. import cv2
  16. import colorsys
  17. import numpy as np
  18. import paddlex.utils.logging as logging
  19. from .detection_eval import fixed_linspace, backup_linspace, loadRes
  20. def visualize_detection(image, result, threshold=0.5, save_dir='./'):
  21. """
  22. Visualize bbox and mask results
  23. """
  24. image_name = os.path.split(image)[-1]
  25. image = cv2.imread(image)
  26. image = draw_bbox_mask(image, result, threshold=threshold)
  27. if save_dir is not None:
  28. if not os.path.exists(save_dir):
  29. os.makedirs(save_dir)
  30. out_path = os.path.join(save_dir, 'visualize_{}'.format(image_name))
  31. cv2.imwrite(out_path, image)
  32. logging.info('The visualized result is saved as {}'.format(out_path))
  33. else:
  34. return image
  35. def visualize_segmentation(image, result, weight=0.6, save_dir='./'):
  36. """
  37. Convert segment result to color image, and save added image.
  38. Args:
  39. image: the path of origin image
  40. result: the predict result of image
  41. weight: the image weight of visual image, and the result weight is (1 - weight)
  42. save_dir: the directory for saving visual image
  43. """
  44. label_map = result['label_map']
  45. color_map = get_color_map_list(256)
  46. color_map = np.array(color_map).astype("uint8")
  47. # Use OpenCV LUT for color mapping
  48. c1 = cv2.LUT(label_map, color_map[:, 0])
  49. c2 = cv2.LUT(label_map, color_map[:, 1])
  50. c3 = cv2.LUT(label_map, color_map[:, 2])
  51. pseudo_img = np.dstack((c1, c2, c3))
  52. im = cv2.imread(image)
  53. vis_result = cv2.addWeighted(im, weight, pseudo_img, 1 - weight, 0)
  54. if save_dir is not None:
  55. if not os.path.exists(save_dir):
  56. os.makedirs(save_dir)
  57. image_name = os.path.split(image)[-1]
  58. out_path = os.path.join(save_dir, 'visualize_{}'.format(image_name))
  59. cv2.imwrite(out_path, vis_result)
  60. logging.info('The visualized result is saved as {}'.format(out_path))
  61. else:
  62. return vis_result
  63. def get_color_map_list(num_classes):
  64. """ Returns the color map for visualizing the segmentation mask,
  65. which can support arbitrary number of classes.
  66. Args:
  67. num_classes: Number of classes
  68. Returns:
  69. The color map
  70. """
  71. color_map = num_classes * [0, 0, 0]
  72. for i in range(0, num_classes):
  73. j = 0
  74. lab = i
  75. while lab:
  76. color_map[i * 3] |= (((lab >> 0) & 1) << (7 - j))
  77. color_map[i * 3 + 1] |= (((lab >> 1) & 1) << (7 - j))
  78. color_map[i * 3 + 2] |= (((lab >> 2) & 1) << (7 - j))
  79. j += 1
  80. lab >>= 3
  81. color_map = [color_map[i:i + 3] for i in range(0, len(color_map), 3)]
  82. return color_map
  83. # expand an array of boxes by a given scale.
  84. def expand_boxes(boxes, scale):
  85. """
  86. """
  87. w_half = (boxes[:, 2] - boxes[:, 0]) * .5
  88. h_half = (boxes[:, 3] - boxes[:, 1]) * .5
  89. x_c = (boxes[:, 2] + boxes[:, 0]) * .5
  90. y_c = (boxes[:, 3] + boxes[:, 1]) * .5
  91. w_half *= scale
  92. h_half *= scale
  93. boxes_exp = np.zeros(boxes.shape)
  94. boxes_exp[:, 0] = x_c - w_half
  95. boxes_exp[:, 2] = x_c + w_half
  96. boxes_exp[:, 1] = y_c - h_half
  97. boxes_exp[:, 3] = y_c + h_half
  98. return boxes_exp
  99. def clip_bbox(bbox):
  100. xmin = max(min(bbox[0], 1.), 0.)
  101. ymin = max(min(bbox[1], 1.), 0.)
  102. xmax = max(min(bbox[2], 1.), 0.)
  103. ymax = max(min(bbox[3], 1.), 0.)
  104. return xmin, ymin, xmax, ymax
  105. def draw_bbox_mask(image, results, threshold=0.5):
  106. import matplotlib
  107. matplotlib.use('Agg')
  108. import matplotlib as mpl
  109. import matplotlib.figure as mplfigure
  110. import matplotlib.colors as mplc
  111. from matplotlib.backends.backend_agg import FigureCanvasAgg
  112. # refer to https://github.com/facebookresearch/detectron2/blob/master/detectron2/utils/visualizer.py
  113. def _change_color_brightness(color, brightness_factor):
  114. assert brightness_factor >= -1.0 and brightness_factor <= 1.0
  115. color = mplc.to_rgb(color)
  116. polygon_color = colorsys.rgb_to_hls(*mplc.to_rgb(color))
  117. modified_lightness = polygon_color[1] + (
  118. brightness_factor * polygon_color[1])
  119. modified_lightness = 0.0 if modified_lightness < 0.0 else modified_lightness
  120. modified_lightness = 1.0 if modified_lightness > 1.0 else modified_lightness
  121. modified_color = colorsys.hls_to_rgb(
  122. polygon_color[0], modified_lightness, polygon_color[2])
  123. return modified_color
  124. _SMALL_OBJECT_AREA_THRESH = 1000
  125. # setup figure
  126. width, height = image.shape[1], image.shape[0]
  127. scale = 1
  128. fig = mplfigure.Figure(frameon=False)
  129. dpi = fig.get_dpi()
  130. fig.set_size_inches(
  131. (width * scale + 1e-2) / dpi,
  132. (height * scale + 1e-2) / dpi,
  133. )
  134. canvas = FigureCanvasAgg(fig)
  135. ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
  136. ax.axis("off")
  137. ax.set_xlim(0.0, width)
  138. ax.set_ylim(height)
  139. default_font_size = max(np.sqrt(height * width) // 90, 10 // scale)
  140. linewidth = max(default_font_size / 4, 1)
  141. labels = list()
  142. for dt in np.array(results):
  143. if dt['category'] not in labels:
  144. labels.append(dt['category'])
  145. color_map = get_color_map_list(256)
  146. keep_results = []
  147. areas = []
  148. for dt in np.array(results):
  149. cname, bbox, score = dt['category'], dt['bbox'], dt['score']
  150. if score < threshold:
  151. continue
  152. keep_results.append(dt)
  153. areas.append(bbox[2] * bbox[3])
  154. areas = np.asarray(areas)
  155. sorted_idxs = np.argsort(-areas).tolist()
  156. keep_results = [keep_results[k]
  157. for k in sorted_idxs] if len(keep_results) > 0 else []
  158. for dt in np.array(keep_results):
  159. cname, bbox, score = dt['category'], dt['bbox'], dt['score']
  160. xmin, ymin, w, h = bbox
  161. xmax = xmin + w
  162. ymax = ymin + h
  163. color = tuple(color_map[labels.index(cname) + 2])
  164. color = [c / 255. for c in color]
  165. # draw bbox
  166. ax.add_patch(
  167. mpl.patches.Rectangle(
  168. (xmin, ymin),
  169. w,
  170. h,
  171. fill=False,
  172. edgecolor=color,
  173. linewidth=linewidth * scale,
  174. alpha=0.8,
  175. linestyle="-",
  176. ))
  177. # draw mask
  178. if 'mask' in dt:
  179. mask = dt['mask']
  180. mask = np.ascontiguousarray(mask)
  181. res = cv2.findContours(
  182. mask.astype("uint8"), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
  183. hierarchy = res[-1]
  184. alpha = 0.5
  185. if hierarchy is not None:
  186. has_holes = (hierarchy.reshape(-1, 4)[:, 3] >= 0).sum() > 0
  187. res = res[-2]
  188. res = [x.flatten() for x in res]
  189. res = [x for x in res if len(x) >= 6]
  190. for segment in res:
  191. segment = segment.reshape(-1, 2)
  192. edge_color = mplc.to_rgb(color) + (1, )
  193. polygon = mpl.patches.Polygon(
  194. segment,
  195. fill=True,
  196. facecolor=mplc.to_rgb(color) + (alpha, ),
  197. edgecolor=edge_color,
  198. linewidth=max(default_font_size // 15 * scale, 1),
  199. )
  200. ax.add_patch(polygon)
  201. # draw label
  202. text_pos = (xmin, ymin)
  203. horiz_align = "left"
  204. instance_area = w * h
  205. if (instance_area < _SMALL_OBJECT_AREA_THRESH * scale
  206. or h < 40 * scale):
  207. if ymin >= height - 5:
  208. text_pos = (xmin, ymin)
  209. else:
  210. text_pos = (xmin, ymax)
  211. height_ratio = h / np.sqrt(height * width)
  212. font_size = (np.clip((height_ratio - 0.02) / 0.08 + 1, 1.2, 2) * 0.5 *
  213. default_font_size)
  214. text = "{} {:.2f}".format(cname, score)
  215. color = np.maximum(list(mplc.to_rgb(color)), 0.2)
  216. color[np.argmax(color)] = max(0.8, np.max(color))
  217. color = _change_color_brightness(color, brightness_factor=0.7)
  218. ax.text(
  219. text_pos[0],
  220. text_pos[1],
  221. text,
  222. size=font_size * scale,
  223. family="sans-serif",
  224. bbox={
  225. "facecolor": "black",
  226. "alpha": 0.8,
  227. "pad": 0.7,
  228. "edgecolor": "none"
  229. },
  230. verticalalignment="top",
  231. horizontalalignment=horiz_align,
  232. color=color,
  233. zorder=10,
  234. rotation=0,
  235. )
  236. s, (width, height) = canvas.print_to_buffer()
  237. buffer = np.frombuffer(s, dtype="uint8")
  238. img_rgba = buffer.reshape(height, width, 4)
  239. rgb, alpha = np.split(img_rgba, [3], axis=2)
  240. try:
  241. import numexpr as ne
  242. visualized_image = ne.evaluate(
  243. "image * (1 - alpha / 255.0) + rgb * (alpha / 255.0)")
  244. except ImportError:
  245. alpha = alpha.astype("float32") / 255.0
  246. visualized_image = image * (1 - alpha) + rgb * alpha
  247. visualized_image = visualized_image.astype("uint8")
  248. return visualized_image
  249. def draw_pr_curve(eval_details_file=None,
  250. gt=None,
  251. pred_bbox=None,
  252. pred_mask=None,
  253. iou_thresh=0.5,
  254. save_dir='./'):
  255. if eval_details_file is not None:
  256. import json
  257. with open(eval_details_file, 'r') as f:
  258. eval_details = json.load(f)
  259. pred_bbox = eval_details['bbox']
  260. if 'mask' in eval_details:
  261. pred_mask = eval_details['mask']
  262. gt = eval_details['gt']
  263. if gt is None or pred_bbox is None:
  264. raise Exception(
  265. "gt/pred_bbox/pred_mask is None now, please set right eval_details_file or gt/pred_bbox/pred_mask."
  266. )
  267. if pred_bbox is not None and len(pred_bbox) == 0:
  268. raise Exception("There is no predicted bbox.")
  269. if pred_mask is not None and len(pred_mask) == 0:
  270. raise Exception("There is no predicted mask.")
  271. import matplotlib
  272. matplotlib.use('Agg')
  273. import matplotlib.pyplot as plt
  274. from pycocotools.coco import COCO
  275. from pycocotools.cocoeval import COCOeval
  276. coco = COCO()
  277. coco.dataset = gt
  278. coco.createIndex()
  279. def _summarize(coco_gt, ap=1, iouThr=None, areaRng='all', maxDets=100):
  280. p = coco_gt.params
  281. aind = [i for i, aRng in enumerate(p.areaRngLbl) if aRng == areaRng]
  282. mind = [i for i, mDet in enumerate(p.maxDets) if mDet == maxDets]
  283. if ap == 1:
  284. # dimension of precision: [TxRxKxAxM]
  285. s = coco_gt.eval['precision']
  286. # IoU
  287. if iouThr is not None:
  288. t = np.where(iouThr == p.iouThrs)[0]
  289. s = s[t]
  290. s = s[:, :, :, aind, mind]
  291. else:
  292. # dimension of recall: [TxKxAxM]
  293. s = coco_gt.eval['recall']
  294. if iouThr is not None:
  295. t = np.where(iouThr == p.iouThrs)[0]
  296. s = s[t]
  297. s = s[:, :, aind, mind]
  298. if len(s[s > -1]) == 0:
  299. mean_s = -1
  300. else:
  301. mean_s = np.mean(s[s > -1])
  302. return mean_s
  303. def cal_pr(coco_gt, coco_dt, iou_thresh, save_dir, style='bbox'):
  304. from pycocotools.cocoeval import COCOeval
  305. coco_dt = loadRes(coco_gt, coco_dt)
  306. np.linspace = fixed_linspace
  307. coco_eval = COCOeval(coco_gt, coco_dt, style)
  308. coco_eval.params.iouThrs = np.linspace(
  309. iou_thresh, iou_thresh, 1, endpoint=True)
  310. np.linspace = backup_linspace
  311. coco_eval.evaluate()
  312. coco_eval.accumulate()
  313. stats = _summarize(coco_eval, iouThr=iou_thresh)
  314. catIds = coco_gt.getCatIds()
  315. if len(catIds) != coco_eval.eval['precision'].shape[2]:
  316. raise Exception(
  317. "The category number must be same as the third dimension of precisions."
  318. )
  319. x = np.arange(0.0, 1.01, 0.01)
  320. color_map = get_color_map_list(256)[1:256]
  321. plt.subplot(1, 2, 1)
  322. plt.title(style + " precision-recall IoU={}".format(iou_thresh))
  323. plt.xlabel("recall")
  324. plt.ylabel("precision")
  325. plt.xlim(0, 1.01)
  326. plt.ylim(0, 1.01)
  327. plt.grid(linestyle='--', linewidth=1)
  328. plt.plot([0, 1], [0, 1], 'r--', linewidth=1)
  329. my_x_ticks = np.arange(0, 1.01, 0.1)
  330. my_y_ticks = np.arange(0, 1.01, 0.1)
  331. plt.xticks(my_x_ticks, fontsize=5)
  332. plt.yticks(my_y_ticks, fontsize=5)
  333. for idx, catId in enumerate(catIds):
  334. pr_array = coco_eval.eval['precision'][0, :, idx, 0, 2]
  335. precision = pr_array[pr_array > -1]
  336. ap = np.mean(precision) if precision.size else float('nan')
  337. nm = coco_gt.loadCats(catId)[0]['name'] + ' AP={:0.2f}'.format(
  338. float(ap * 100))
  339. color = tuple(color_map[idx])
  340. color = [float(c) / 255 for c in color]
  341. color.append(0.75)
  342. plt.plot(x, pr_array, color=color, label=nm, linewidth=1)
  343. plt.legend(loc="lower left", fontsize=5)
  344. plt.subplot(1, 2, 2)
  345. plt.title(style + " score-recall IoU={}".format(iou_thresh))
  346. plt.xlabel('recall')
  347. plt.ylabel('score')
  348. plt.xlim(0, 1.01)
  349. plt.ylim(0, 1.01)
  350. plt.grid(linestyle='--', linewidth=1)
  351. plt.xticks(my_x_ticks, fontsize=5)
  352. plt.yticks(my_y_ticks, fontsize=5)
  353. for idx, catId in enumerate(catIds):
  354. nm = coco_gt.loadCats(catId)[0]['name']
  355. sr_array = coco_eval.eval['scores'][0, :, idx, 0, 2]
  356. color = tuple(color_map[idx])
  357. color = [float(c) / 255 for c in color]
  358. color.append(0.75)
  359. plt.plot(x, sr_array, color=color, label=nm, linewidth=1)
  360. plt.legend(loc="lower left", fontsize=5)
  361. plt.savefig(
  362. os.path.join(save_dir, "./{}_pr_curve(iou-{}).png".format(
  363. style, iou_thresh)),
  364. dpi=800)
  365. plt.close()
  366. if not os.path.exists(save_dir):
  367. os.makedirs(save_dir)
  368. cal_pr(coco, pred_bbox, iou_thresh, save_dir, style='bbox')
  369. if pred_mask is not None:
  370. cal_pr(coco, pred_mask, iou_thresh, save_dir, style='segm')