visualize.py 16 KB

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