visualize.py 15 KB

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