visualize.py 14 KB

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