visualize.py 16 KB

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