visualize.py 15 KB

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