visualize.py 16 KB

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