visualize.py 15.7 KB
Newer Older
M
mamingjie-China 已提交
1
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
J
jiangjiajun 已提交
2
#
F
FlyingQianMM 已提交
3 4 5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
J
jiangjiajun 已提交
6
#
F
FlyingQianMM 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
J
jiangjiajun 已提交
8
#
F
FlyingQianMM 已提交
9 10 11 12 13
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
J
jiangjiajun 已提交
14

F
FlyingQianMM 已提交
15
# -*- coding: utf-8 -*
J
jiangjiajun 已提交
16 17
import os
import cv2
F
FlyingQianMM 已提交
18
import colorsys
J
jiangjiajun 已提交
19
import numpy as np
20
import time
F
FlyingQianMM 已提交
21
import paddlex.utils.logging as logging
F
FlyingQianMM 已提交
22
from .detection_eval import fixed_linspace, backup_linspace, loadRes
F
FlyingQianMM 已提交
23
from paddlex.cv.datasets.dataset import is_pic
J
jiangjiajun 已提交
24 25


F
FlyingQianMM 已提交
26
def visualize_detection(image, result, threshold=0.5, save_dir='./'):
J
jiangjiajun 已提交
27 28 29 30
    """
        Visualize bbox and mask results
    """

31
    if isinstance(image, np.ndarray):
J
jiangjiajun 已提交
32
        image_name = str(int(time.time() * 1000)) + '.jpg'
33 34
    else:
        image_name = os.path.split(image)[-1]
F
FlyingQianMM 已提交
35
        image = cv2.imread(image)
36

37
    image = draw_bbox_mask(image, result, threshold=threshold)
J
jiangjiajun 已提交
38 39 40 41
    if save_dir is not None:
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
        out_path = os.path.join(save_dir, 'visualize_{}'.format(image_name))
F
FlyingQianMM 已提交
42
        cv2.imwrite(out_path, image)
F
FlyingQianMM 已提交
43
        logging.info('The visualized result is saved as {}'.format(out_path))
J
jiangjiajun 已提交
44 45 46 47
    else:
        return image


F
FlyingQianMM 已提交
48 49 50 51 52
def visualize_segmentation(image,
                           result,
                           weight=0.6,
                           save_dir='./',
                           color=None):
J
jiangjiajun 已提交
53 54 55 56 57 58 59
    """
    Convert segment result to color image, and save added image.
    Args:
        image: the path of origin image
        result: the predict result of image
        weight: the image weight of visual image, and the result weight is (1 - weight)
        save_dir: the directory for saving visual image
F
FlyingQianMM 已提交
60
        color: the list of a BGR-mode color for each label.
J
jiangjiajun 已提交
61 62 63
    """
    label_map = result['label_map']
    color_map = get_color_map_list(256)
F
FlyingQianMM 已提交
64 65
    if color is not None:
        color_map[0:len(color) // 3][:] = color
J
jiangjiajun 已提交
66
    color_map = np.array(color_map).astype("uint8")
F
FlyingQianMM 已提交
67

J
jiangjiajun 已提交
68 69 70 71 72 73
    # Use OpenCV LUT for color mapping
    c1 = cv2.LUT(label_map, color_map[:, 0])
    c2 = cv2.LUT(label_map, color_map[:, 1])
    c3 = cv2.LUT(label_map, color_map[:, 2])
    pseudo_img = np.dstack((c1, c2, c3))

74 75
    if isinstance(image, np.ndarray):
        im = image
J
jiangjiajun 已提交
76
        image_name = str(int(time.time() * 1000)) + '.jpg'
F
FlyingQianMM 已提交
77 78 79 80 81
        if image.shape[2] != 3:
            logging.info(
                "The image is not 3-channel array, so predicted label map is shown as a pseudo color image."
            )
            weight = 0.
82 83
    else:
        image_name = os.path.split(image)[-1]
F
FlyingQianMM 已提交
84 85 86 87 88 89 90 91
        if not is_pic(image):
            logging.info(
                "The image cannot be opened by opencv, so predicted label map is shown as a pseudo color image."
            )
            image_name = image_name.split('.')[0] + '.jpg'
            weight = 0.
        else:
            im = cv2.imread(image)
92

F
FlyingQianMM 已提交
93 94 95
    if abs(weight) < 1e-5:
        vis_result = pseudo_img
    else:
F
FlyingQianMM 已提交
96 97 98
        vis_result = cv2.addWeighted(im, weight,
                                     pseudo_img.astype('float32'), 1 - weight,
                                     0)
J
jiangjiajun 已提交
99 100 101 102 103 104

    if save_dir is not None:
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
        out_path = os.path.join(save_dir, 'visualize_{}'.format(image_name))
        cv2.imwrite(out_path, vis_result)
F
FlyingQianMM 已提交
105
        logging.info('The visualized result is saved as {}'.format(out_path))
J
jiangjiajun 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    else:
        return vis_result


def get_color_map_list(num_classes):
    """ Returns the color map for visualizing the segmentation mask,
        which can support arbitrary number of classes.
    Args:
        num_classes: Number of classes
    Returns:
        The color map
    """
    color_map = num_classes * [0, 0, 0]
    for i in range(0, num_classes):
        j = 0
        lab = i
        while lab:
            color_map[i * 3] |= (((lab >> 0) & 1) << (7 - j))
            color_map[i * 3 + 1] |= (((lab >> 1) & 1) << (7 - j))
            color_map[i * 3 + 2] |= (((lab >> 2) & 1) << (7 - j))
            j += 1
            lab >>= 3
    color_map = [color_map[i:i + 3] for i in range(0, len(color_map), 3)]
    return color_map


# expand an array of boxes by a given scale.
def expand_boxes(boxes, scale):
    """
        """
    w_half = (boxes[:, 2] - boxes[:, 0]) * .5
    h_half = (boxes[:, 3] - boxes[:, 1]) * .5
    x_c = (boxes[:, 2] + boxes[:, 0]) * .5
    y_c = (boxes[:, 3] + boxes[:, 1]) * .5

    w_half *= scale
    h_half *= scale

    boxes_exp = np.zeros(boxes.shape)
    boxes_exp[:, 0] = x_c - w_half
    boxes_exp[:, 2] = x_c + w_half
    boxes_exp[:, 1] = y_c - h_half
    boxes_exp[:, 3] = y_c + h_half

    return boxes_exp


def clip_bbox(bbox):
    xmin = max(min(bbox[0], 1.), 0.)
    ymin = max(min(bbox[1], 1.), 0.)
    xmax = max(min(bbox[2], 1.), 0.)
    ymax = max(min(bbox[3], 1.), 0.)
    return xmin, ymin, xmax, ymax


F
FlyingQianMM 已提交
161
def draw_bbox_mask(image, results, threshold=0.5):
162 163 164 165 166 167 168
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib as mpl
    import matplotlib.figure as mplfigure
    import matplotlib.colors as mplc
    from matplotlib.backends.backend_agg import FigureCanvasAgg

F
FlyingQianMM 已提交
169
    # refer to  https://github.com/facebookresearch/detectron2/blob/master/detectron2/utils/visualizer.py
F
FlyingQianMM 已提交
170 171 172 173
    def _change_color_brightness(color, brightness_factor):
        assert brightness_factor >= -1.0 and brightness_factor <= 1.0
        color = mplc.to_rgb(color)
        polygon_color = colorsys.rgb_to_hls(*mplc.to_rgb(color))
J
jiangjiajun 已提交
174 175
        modified_lightness = polygon_color[1] + (brightness_factor *
                                                 polygon_color[1])
F
FlyingQianMM 已提交
176 177 178 179 180 181
        modified_lightness = 0.0 if modified_lightness < 0.0 else modified_lightness
        modified_lightness = 1.0 if modified_lightness > 1.0 else modified_lightness
        modified_color = colorsys.hls_to_rgb(
            polygon_color[0], modified_lightness, polygon_color[2])
        return modified_color

F
FlyingQianMM 已提交
182 183 184 185 186 187 188 189
    _SMALL_OBJECT_AREA_THRESH = 1000
    # setup figure
    width, height = image.shape[1], image.shape[0]
    scale = 1
    fig = mplfigure.Figure(frameon=False)
    dpi = fig.get_dpi()
    fig.set_size_inches(
        (width * scale + 1e-2) / dpi,
J
jiangjiajun 已提交
190
        (height * scale + 1e-2) / dpi, )
F
FlyingQianMM 已提交
191 192 193 194 195 196 197 198
    canvas = FigureCanvasAgg(fig)
    ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
    ax.axis("off")
    ax.set_xlim(0.0, width)
    ax.set_ylim(height)
    default_font_size = max(np.sqrt(height * width) // 90, 10 // scale)
    linewidth = max(default_font_size / 4, 1)

J
jiangjiajun 已提交
199 200 201 202
    labels = list()
    for dt in np.array(results):
        if dt['category'] not in labels:
            labels.append(dt['category'])
F
FlyingQianMM 已提交
203
    color_map = get_color_map_list(256)
J
jiangjiajun 已提交
204

F
FlyingQianMM 已提交
205 206
    keep_results = []
    areas = []
J
jiangjiajun 已提交
207 208 209 210
    for dt in np.array(results):
        cname, bbox, score = dt['category'], dt['bbox'], dt['score']
        if score < threshold:
            continue
F
FlyingQianMM 已提交
211 212 213 214 215 216
        keep_results.append(dt)
        areas.append(bbox[2] * bbox[3])
    areas = np.asarray(areas)
    sorted_idxs = np.argsort(-areas).tolist()
    keep_results = [keep_results[k]
                    for k in sorted_idxs] if len(keep_results) > 0 else []
J
jiangjiajun 已提交
217

F
FlyingQianMM 已提交
218 219
    for dt in np.array(keep_results):
        cname, bbox, score = dt['category'], dt['bbox'], dt['score']
J
jiangjiajun 已提交
220 221 222 223
        xmin, ymin, w, h = bbox
        xmax = xmin + w
        ymax = ymin + h

F
FlyingQianMM 已提交
224 225
        color = tuple(color_map[labels.index(cname) + 2])
        color = [c / 255. for c in color]
J
jiangjiajun 已提交
226
        # draw bbox
F
FlyingQianMM 已提交
227 228 229 230 231 232 233 234
        ax.add_patch(
            mpl.patches.Rectangle(
                (xmin, ymin),
                w,
                h,
                fill=False,
                edgecolor=color,
                linewidth=linewidth * scale,
F
FlyingQianMM 已提交
235
                alpha=0.8,
J
jiangjiajun 已提交
236
                linestyle="-", ))
J
jiangjiajun 已提交
237 238 239 240

        # draw mask
        if 'mask' in dt:
            mask = dt['mask']
F
FlyingQianMM 已提交
241 242 243 244
            mask = np.ascontiguousarray(mask)
            res = cv2.findContours(
                mask.astype("uint8"), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
            hierarchy = res[-1]
F
FlyingQianMM 已提交
245
            alpha = 0.5
F
FlyingQianMM 已提交
246 247 248 249 250 251 252 253 254 255 256 257 258
            if hierarchy is not None:
                has_holes = (hierarchy.reshape(-1, 4)[:, 3] >= 0).sum() > 0
                res = res[-2]
                res = [x.flatten() for x in res]
                res = [x for x in res if len(x) >= 6]
                for segment in res:
                    segment = segment.reshape(-1, 2)
                    edge_color = mplc.to_rgb(color) + (1, )
                    polygon = mpl.patches.Polygon(
                        segment,
                        fill=True,
                        facecolor=mplc.to_rgb(color) + (alpha, ),
                        edgecolor=edge_color,
J
jiangjiajun 已提交
259
                        linewidth=max(default_font_size // 15 * scale, 1), )
F
FlyingQianMM 已提交
260 261 262 263 264 265
                    ax.add_patch(polygon)

        # draw label
        text_pos = (xmin, ymin)
        horiz_align = "left"
        instance_area = w * h
J
jiangjiajun 已提交
266 267
        if (instance_area < _SMALL_OBJECT_AREA_THRESH * scale or
                h < 40 * scale):
F
FlyingQianMM 已提交
268 269 270 271 272
            if ymin >= height - 5:
                text_pos = (xmin, ymin)
            else:
                text_pos = (xmin, ymax)
        height_ratio = h / np.sqrt(height * width)
J
jiangjiajun 已提交
273 274
        font_size = (np.clip((height_ratio - 0.02) / 0.08 + 1, 1.2,
                             2) * 0.5 * default_font_size)
F
FlyingQianMM 已提交
275 276 277
        text = "{} {:.2f}".format(cname, score)
        color = np.maximum(list(mplc.to_rgb(color)), 0.2)
        color[np.argmax(color)] = max(0.8, np.max(color))
F
FlyingQianMM 已提交
278
        color = _change_color_brightness(color, brightness_factor=0.7)
F
FlyingQianMM 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
        ax.text(
            text_pos[0],
            text_pos[1],
            text,
            size=font_size * scale,
            family="sans-serif",
            bbox={
                "facecolor": "black",
                "alpha": 0.8,
                "pad": 0.7,
                "edgecolor": "none"
            },
            verticalalignment="top",
            horizontalalignment=horiz_align,
            color=color,
            zorder=10,
J
jiangjiajun 已提交
295
            rotation=0, )
F
FlyingQianMM 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313

    s, (width, height) = canvas.print_to_buffer()
    buffer = np.frombuffer(s, dtype="uint8")

    img_rgba = buffer.reshape(height, width, 4)
    rgb, alpha = np.split(img_rgba, [3], axis=2)

    try:
        import numexpr as ne
        visualized_image = ne.evaluate(
            "image * (1 - alpha / 255.0) + rgb * (alpha / 255.0)")
    except ImportError:
        alpha = alpha.astype("float32") / 255.0
        visualized_image = image * (1 - alpha) + rgb * alpha

    visualized_image = visualized_image.astype("uint8")

    return visualized_image
F
FlyingQianMM 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337


def draw_pr_curve(eval_details_file=None,
                  gt=None,
                  pred_bbox=None,
                  pred_mask=None,
                  iou_thresh=0.5,
                  save_dir='./'):
    if eval_details_file is not None:
        import json
        with open(eval_details_file, 'r') as f:
            eval_details = json.load(f)
            pred_bbox = eval_details['bbox']
            if 'mask' in eval_details:
                pred_mask = eval_details['mask']
            gt = eval_details['gt']
    if gt is None or pred_bbox is None:
        raise Exception(
            "gt/pred_bbox/pred_mask is None now, please set right eval_details_file or gt/pred_bbox/pred_mask."
        )
    if pred_bbox is not None and len(pred_bbox) == 0:
        raise Exception("There is no predicted bbox.")
    if pred_mask is not None and len(pred_mask) == 0:
        raise Exception("There is no predicted mask.")
338 339 340
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
F
FlyingQianMM 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
    from pycocotools.coco import COCO
    from pycocotools.cocoeval import COCOeval
    coco = COCO()
    coco.dataset = gt
    coco.createIndex()

    def _summarize(coco_gt, ap=1, iouThr=None, areaRng='all', maxDets=100):
        p = coco_gt.params
        aind = [i for i, aRng in enumerate(p.areaRngLbl) if aRng == areaRng]
        mind = [i for i, mDet in enumerate(p.maxDets) if mDet == maxDets]
        if ap == 1:
            # dimension of precision: [TxRxKxAxM]
            s = coco_gt.eval['precision']
            # IoU
            if iouThr is not None:
                t = np.where(iouThr == p.iouThrs)[0]
                s = s[t]
            s = s[:, :, :, aind, mind]
        else:
            # dimension of recall: [TxKxAxM]
            s = coco_gt.eval['recall']
            if iouThr is not None:
                t = np.where(iouThr == p.iouThrs)[0]
                s = s[t]
            s = s[:, :, aind, mind]
        if len(s[s > -1]) == 0:
            mean_s = -1
        else:
            mean_s = np.mean(s[s > -1])
        return mean_s

    def cal_pr(coco_gt, coco_dt, iou_thresh, save_dir, style='bbox'):
        from pycocotools.cocoeval import COCOeval
        coco_dt = loadRes(coco_gt, coco_dt)
        np.linspace = fixed_linspace
        coco_eval = COCOeval(coco_gt, coco_dt, style)
        coco_eval.params.iouThrs = np.linspace(
            iou_thresh, iou_thresh, 1, endpoint=True)
        np.linspace = backup_linspace
        coco_eval.evaluate()
        coco_eval.accumulate()
        stats = _summarize(coco_eval, iouThr=iou_thresh)
        catIds = coco_gt.getCatIds()
        if len(catIds) != coco_eval.eval['precision'].shape[2]:
            raise Exception(
                "The category number must be same as the third dimension of precisions."
            )
        x = np.arange(0.0, 1.01, 0.01)
        color_map = get_color_map_list(256)[1:256]

        plt.subplot(1, 2, 1)
        plt.title(style + " precision-recall IoU={}".format(iou_thresh))
        plt.xlabel("recall")
        plt.ylabel("precision")
        plt.xlim(0, 1.01)
        plt.ylim(0, 1.01)
        plt.grid(linestyle='--', linewidth=1)
        plt.plot([0, 1], [0, 1], 'r--', linewidth=1)
        my_x_ticks = np.arange(0, 1.01, 0.1)
        my_y_ticks = np.arange(0, 1.01, 0.1)
        plt.xticks(my_x_ticks, fontsize=5)
        plt.yticks(my_y_ticks, fontsize=5)
        for idx, catId in enumerate(catIds):
            pr_array = coco_eval.eval['precision'][0, :, idx, 0, 2]
            precision = pr_array[pr_array > -1]
            ap = np.mean(precision) if precision.size else float('nan')
            nm = coco_gt.loadCats(catId)[0]['name'] + ' AP={:0.2f}'.format(
                float(ap * 100))
            color = tuple(color_map[idx])
            color = [float(c) / 255 for c in color]
            color.append(0.75)
            plt.plot(x, pr_array, color=color, label=nm, linewidth=1)
        plt.legend(loc="lower left", fontsize=5)

        plt.subplot(1, 2, 2)
        plt.title(style + " score-recall IoU={}".format(iou_thresh))
        plt.xlabel('recall')
        plt.ylabel('score')
        plt.xlim(0, 1.01)
        plt.ylim(0, 1.01)
        plt.grid(linestyle='--', linewidth=1)
        plt.xticks(my_x_ticks, fontsize=5)
        plt.yticks(my_y_ticks, fontsize=5)
        for idx, catId in enumerate(catIds):
            nm = coco_gt.loadCats(catId)[0]['name']
            sr_array = coco_eval.eval['scores'][0, :, idx, 0, 2]
            color = tuple(color_map[idx])
            color = [float(c) / 255 for c in color]
            color.append(0.75)
            plt.plot(x, sr_array, color=color, label=nm, linewidth=1)
431
        plt.legend(loc="lower left", fontsize=5)
F
FlyingQianMM 已提交
432
        plt.savefig(
M
mamingjie-China 已提交
433 434 435
            os.path.join(
                save_dir,
                "./{}_pr_curve(iou-{}).png".format(style, iou_thresh)),
F
FlyingQianMM 已提交
436 437 438
            dpi=800)
        plt.close()

F
FlyingQianMM 已提交
439 440
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
F
FlyingQianMM 已提交
441 442 443
    cal_pr(coco, pred_bbox, iou_thresh, save_dir, style='bbox')
    if pred_mask is not None:
        cal_pr(coco, pred_mask, iou_thresh, save_dir, style='segm')