visualize.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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 colorsys
  17. import numpy as np
  18. import time
  19. import pycocotools.mask as mask_util
  20. import paddlex.utils.logging as logging
  21. from paddlex.utils import is_pic
  22. from .det_metrics.coco_utils import loadRes
  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 at {}'.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. _SMALL_OBJECT_AREA_THRESH = 1000
  146. height, width = image.shape[:2]
  147. default_font_scale = max(np.sqrt(height * width) // 900, .5)
  148. linewidth = max(default_font_scale / 40, 2)
  149. labels = list()
  150. for dt in results:
  151. if dt['category'] not in labels:
  152. labels.append(dt['category'])
  153. if color_map is None:
  154. color_map = get_color_map_list(len(labels) + 2)[2:]
  155. else:
  156. color_map = np.asarray(color_map)
  157. if color_map.shape[0] != len(labels) or color_map.shape[1] != 3:
  158. raise Exception(
  159. "The shape for color_map is required to be {}x3, but recieved shape is {}x{}.".
  160. format(len(labels), color_map.shape))
  161. if np.max(color_map) > 255 or np.min(color_map) < 0:
  162. raise ValueError(
  163. " The values in color_map should be within 0-255 range.")
  164. keep_results = []
  165. areas = []
  166. for dt in results:
  167. cname, bbox, score = dt['category'], dt['bbox'], dt['score']
  168. if score < threshold:
  169. continue
  170. keep_results.append(dt)
  171. areas.append(bbox[2] * bbox[3])
  172. areas = np.asarray(areas)
  173. sorted_idxs = np.argsort(-areas).tolist()
  174. keep_results = [keep_results[k]
  175. for k in sorted_idxs] if keep_results else []
  176. for dt in keep_results:
  177. cname, bbox, score = dt['category'], dt['bbox'], dt['score']
  178. bbox = list(map(int, bbox))
  179. xmin, ymin, w, h = bbox
  180. xmax = xmin + w
  181. ymax = ymin + h
  182. color = tuple(color_map[labels.index(cname)])
  183. # draw bbox
  184. image = cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color,
  185. linewidth)
  186. # draw mask
  187. if 'mask' in dt:
  188. mask = mask_util.decode(dt['mask']) * 255
  189. image = image.astype('float32')
  190. alpha = .7
  191. w_ratio = .4
  192. color_mask = np.asarray(color, dtype=np.int)
  193. for c in range(3):
  194. color_mask[c] = color_mask[c] * (1 - w_ratio) + w_ratio * 255
  195. idx = np.nonzero(mask)
  196. image[idx[0], idx[1], :] *= 1.0 - alpha
  197. image[idx[0], idx[1], :] += alpha * color_mask
  198. image = image.astype("uint8")
  199. contours = cv2.findContours(
  200. mask.astype("uint8"), cv2.RETR_CCOMP,
  201. cv2.CHAIN_APPROX_NONE)[-2]
  202. image = cv2.drawContours(
  203. image,
  204. contours,
  205. contourIdx=-1,
  206. color=color,
  207. thickness=1,
  208. lineType=cv2.LINE_AA)
  209. # draw label
  210. text_pos = (xmin, ymin)
  211. instance_area = w * h
  212. if (instance_area < _SMALL_OBJECT_AREA_THRESH or h < 40):
  213. if ymin >= height - 5:
  214. text_pos = (xmin, ymin)
  215. else:
  216. text_pos = (xmin, ymax)
  217. height_ratio = h / np.sqrt(height * width)
  218. font_scale = (np.clip((height_ratio - 0.02) / 0.08 + 1, 1.2,
  219. 2) * 0.5 * default_font_scale)
  220. text = "{} {:.2f}".format(cname, score)
  221. (tw, th), baseline = cv2.getTextSize(
  222. text,
  223. fontFace=cv2.FONT_HERSHEY_DUPLEX,
  224. fontScale=font_scale,
  225. thickness=1)
  226. image = cv2.rectangle(
  227. image,
  228. text_pos, (text_pos[0] + tw, text_pos[1] + th + baseline),
  229. color=color,
  230. thickness=-1)
  231. image = cv2.putText(
  232. image,
  233. text, (text_pos[0], text_pos[1] + th),
  234. fontFace=cv2.FONT_HERSHEY_DUPLEX,
  235. fontScale=font_scale,
  236. color=(255, 255, 255),
  237. thickness=1,
  238. lineType=cv2.LINE_AA)
  239. return image
  240. def draw_pr_curve(eval_details_file=None,
  241. gt=None,
  242. pred_bbox=None,
  243. pred_mask=None,
  244. iou_thresh=0.5,
  245. save_dir='./'):
  246. if eval_details_file is not None:
  247. import json
  248. with open(eval_details_file, 'r') as f:
  249. eval_details = json.load(f)
  250. pred_bbox = eval_details['bbox']
  251. if 'mask' in eval_details:
  252. pred_mask = eval_details['mask']
  253. gt = eval_details['gt']
  254. if gt is None or pred_bbox is None:
  255. raise Exception(
  256. "gt/pred_bbox/pred_mask is None now, please set right eval_details_file or gt/pred_bbox/pred_mask."
  257. )
  258. if pred_bbox is not None and len(pred_bbox) == 0:
  259. raise Exception("There is no predicted bbox.")
  260. if pred_mask is not None and len(pred_mask) == 0:
  261. raise Exception("There is no predicted mask.")
  262. import matplotlib
  263. matplotlib.use('Agg')
  264. import matplotlib.pyplot as plt
  265. from pycocotools.coco import COCO
  266. from pycocotools.cocoeval import COCOeval
  267. coco = COCO()
  268. coco.dataset = gt
  269. coco.createIndex()
  270. def _summarize(coco_gt, ap=1, iouThr=None, areaRng='all', maxDets=100):
  271. p = coco_gt.params
  272. aind = [i for i, aRng in enumerate(p.areaRngLbl) if aRng == areaRng]
  273. mind = [i for i, mDet in enumerate(p.maxDets) if mDet == maxDets]
  274. if ap == 1:
  275. # dimension of precision: [TxRxKxAxM]
  276. s = coco_gt.eval['precision']
  277. # IoU
  278. if iouThr is not None:
  279. t = np.where(iouThr == p.iouThrs)[0]
  280. s = s[t]
  281. s = s[:, :, :, aind, mind]
  282. else:
  283. # dimension of recall: [TxKxAxM]
  284. s = coco_gt.eval['recall']
  285. if iouThr is not None:
  286. t = np.where(iouThr == p.iouThrs)[0]
  287. s = s[t]
  288. s = s[:, :, aind, mind]
  289. if len(s[s > -1]) == 0:
  290. mean_s = -1
  291. else:
  292. mean_s = np.mean(s[s > -1])
  293. return mean_s
  294. def cal_pr(coco_gt, coco_dt, iou_thresh, save_dir, style='bbox'):
  295. coco_dt = loadRes(coco_gt, coco_dt)
  296. coco_eval = COCOeval(coco_gt, coco_dt, style)
  297. coco_eval.params.iouThrs = np.linspace(
  298. iou_thresh, iou_thresh, 1, endpoint=True)
  299. coco_eval.evaluate()
  300. coco_eval.accumulate()
  301. stats = _summarize(coco_eval, iouThr=iou_thresh)
  302. catIds = coco_gt.getCatIds()
  303. if len(catIds) != coco_eval.eval['precision'].shape[2]:
  304. raise Exception(
  305. "The category number must be same as the third dimension of precisions."
  306. )
  307. x = np.arange(0.0, 1.01, 0.01)
  308. color_map = get_color_map_list(256)[1:256]
  309. plt.subplot(1, 2, 1)
  310. plt.title(style + " precision-recall IoU={}".format(iou_thresh))
  311. plt.xlabel("recall")
  312. plt.ylabel("precision")
  313. plt.xlim(0, 1.01)
  314. plt.ylim(0, 1.01)
  315. plt.grid(linestyle='--', linewidth=1)
  316. plt.plot([0, 1], [0, 1], 'r--', linewidth=1)
  317. my_x_ticks = np.arange(0, 1.01, 0.1)
  318. my_y_ticks = np.arange(0, 1.01, 0.1)
  319. plt.xticks(my_x_ticks, fontsize=5)
  320. plt.yticks(my_y_ticks, fontsize=5)
  321. for idx, catId in enumerate(catIds):
  322. pr_array = coco_eval.eval['precision'][0, :, idx, 0, 2]
  323. precision = pr_array[pr_array > -1]
  324. ap = np.mean(precision) if precision.size else float('nan')
  325. nm = coco_gt.loadCats(catId)[0]['name'] + ' AP={:0.2f}'.format(
  326. float(ap * 100))
  327. color = tuple(color_map[idx])
  328. color = [float(c) / 255 for c in color]
  329. color.append(0.75)
  330. plt.plot(x, pr_array, color=color, label=nm, linewidth=1)
  331. plt.legend(loc="lower left", fontsize=5)
  332. plt.subplot(1, 2, 2)
  333. plt.title(style + " score-recall IoU={}".format(iou_thresh))
  334. plt.xlabel('recall')
  335. plt.ylabel('score')
  336. plt.xlim(0, 1.01)
  337. plt.ylim(0, 1.01)
  338. plt.grid(linestyle='--', linewidth=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. nm = coco_gt.loadCats(catId)[0]['name']
  343. sr_array = coco_eval.eval['scores'][0, :, idx, 0, 2]
  344. color = tuple(color_map[idx])
  345. color = [float(c) / 255 for c in color]
  346. color.append(0.75)
  347. plt.plot(x, sr_array, color=color, label=nm, linewidth=1)
  348. plt.legend(loc="lower left", fontsize=5)
  349. plt.savefig(
  350. os.path.join(
  351. save_dir,
  352. "./{}_pr_curve(iou-{}).png".format(style, iou_thresh)),
  353. dpi=800)
  354. plt.close()
  355. if not os.path.exists(save_dir):
  356. os.makedirs(save_dir)
  357. cal_pr(coco, pred_bbox, iou_thresh, save_dir, style='bbox')
  358. if pred_mask is not None:
  359. cal_pr(coco, pred_mask, iou_thresh, save_dir, style='segm')