visualize.py 13.1 KB
Newer Older
F
Feng Ni 已提交
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#
# 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
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 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.

from __future__ import division

import os
import cv2
import numpy as np
F
Feng Ni 已提交
20 21
from PIL import Image, ImageDraw, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
W
wangguanzhong 已提交
22
from collections import deque
23 24
from ppdet.utils.compact import imagedraw_textsize_c

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113


def visualize_box_mask(im, results, labels, threshold=0.5):
    """
    Args:
        im (str/np.ndarray): path of image/np.ndarray read by cv2
        results (dict): include 'boxes': np.ndarray: shape:[N,6], N: number of box,
                        matix element:[class, score, x_min, y_min, x_max, y_max]
        labels (list): labels:['class1', ..., 'classn']
        threshold (float): Threshold of score.
    Returns:
        im (PIL.Image.Image): visualized image
    """
    if isinstance(im, str):
        im = Image.open(im).convert('RGB')
    else:
        im = Image.fromarray(im)
    if 'boxes' in results and len(results['boxes']) > 0:
        im = draw_box(im, results['boxes'], labels, threshold=threshold)
    return im


def get_color_map_list(num_classes):
    """
    Args:
        num_classes (int): number of class
    Returns:
        color_map (list): RGB color list
    """
    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


def draw_box(im, np_boxes, labels, threshold=0.5):
    """
    Args:
        im (PIL.Image.Image): PIL image
        np_boxes (np.ndarray): shape:[N,6], N: number of box,
                               matix element:[class, score, x_min, y_min, x_max, y_max]
        labels (list): labels:['class1', ..., 'classn']
        threshold (float): threshold of box
    Returns:
        im (PIL.Image.Image): visualized image
    """
    draw_thickness = min(im.size) // 320
    draw = ImageDraw.Draw(im)
    clsid2color = {}
    color_list = get_color_map_list(len(labels))
    expect_boxes = (np_boxes[:, 1] > threshold) & (np_boxes[:, 0] > -1)
    np_boxes = np_boxes[expect_boxes, :]

    for dt in np_boxes:
        clsid, bbox, score = int(dt[0]), dt[2:], dt[1]
        if clsid not in clsid2color:
            clsid2color[clsid] = color_list[clsid]
        color = tuple(clsid2color[clsid])

        if len(bbox) == 4:
            xmin, ymin, xmax, ymax = bbox
            print('class_id:{:d}, confidence:{:.4f}, left_top:[{:.2f},{:.2f}],'
                  'right_bottom:[{:.2f},{:.2f}]'.format(
                      int(clsid), score, xmin, ymin, xmax, ymax))
            # draw bbox
            draw.line(
                [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin),
                 (xmin, ymin)],
                width=draw_thickness,
                fill=color)
        elif len(bbox) == 8:
            x1, y1, x2, y2, x3, y3, x4, y4 = bbox
            draw.line(
                [(x1, y1), (x2, y2), (x3, y3), (x4, y4), (x1, y1)],
                width=2,
                fill=color)
            xmin = min(x1, x2, x3, x4)
            ymin = min(y1, y2, y3, y4)

        # draw label
        text = "{} {:.4f}".format(labels[clsid], score)
114
        tw, th = imagedraw_textsize_c(draw, text)
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
        draw.rectangle(
            [(xmin + 1, ymin - th), (xmin + tw + 1, ymin)], fill=color)
        draw.text((xmin + 1, ymin - th), text, fill=(255, 255, 255))
    return im


def get_color(idx):
    idx = idx * 3
    color = ((37 * idx) % 255, (17 * idx) % 255, (29 * idx) % 255)
    return color


def plot_tracking(image,
                  tlwhs,
                  obj_ids,
                  scores=None,
                  frame_id=0,
                  fps=0.,
133 134 135
                  ids2names=[],
                  do_entrance_counting=False,
                  entrance=None):
136 137 138
    im = np.ascontiguousarray(np.copy(image))
    im_h, im_w = im.shape[:2]

W
wangguanzhong 已提交
139
    text_scale = max(0.5, image.shape[1] / 3000.)
140 141 142 143 144 145
    text_thickness = 2
    line_thickness = max(1, int(image.shape[1] / 500.))

    cv2.putText(
        im,
        'frame: %d fps: %.2f num: %d' % (frame_id, fps, len(tlwhs)),
W
wangguanzhong 已提交
146 147
        (0, int(15 * text_scale) + 5),
        cv2.FONT_ITALIC,
148
        text_scale, (0, 0, 255),
W
wangguanzhong 已提交
149
        thickness=text_thickness)
150 151 152 153
    for i, tlwh in enumerate(tlwhs):
        x1, y1, w, h = tlwh
        intbox = tuple(map(int, (x1, y1, x1 + w, y1 + h)))
        obj_id = int(obj_ids[i])
W
wangguanzhong 已提交
154
        id_text = 'ID: {}'.format(int(obj_id))
155
        if ids2names != []:
156 157
            assert len(
                ids2names) == 1, "plot_tracking only supports single classes."
W
wangguanzhong 已提交
158
            id_text = 'ID: {}_'.format(ids2names[0]) + id_text
159 160 161 162 163 164
        _line_thickness = 1 if obj_id <= 0 else line_thickness
        color = get_color(abs(obj_id))
        cv2.rectangle(
            im, intbox[0:2], intbox[2:4], color=color, thickness=line_thickness)
        cv2.putText(
            im,
W
wangguanzhong 已提交
165 166 167
            id_text, (intbox[0], intbox[1] - 25),
            cv2.FONT_ITALIC,
            text_scale, (0, 255, 255),
168 169 170
            thickness=text_thickness)

        if scores is not None:
W
wangguanzhong 已提交
171
            text = 'score: {:.2f}'.format(float(scores[i]))
172 173
            cv2.putText(
                im,
W
wangguanzhong 已提交
174 175 176
                text, (intbox[0], intbox[1] - 6),
                cv2.FONT_ITALIC,
                text_scale, (0, 255, 0),
177
                thickness=text_thickness)
178 179 180 181 182 183 184 185
    if do_entrance_counting:
        entrance_line = tuple(map(int, entrance))
        cv2.rectangle(
            im,
            entrance_line[0:2],
            entrance_line[2:4],
            color=(0, 255, 255),
            thickness=line_thickness)
186 187 188 189 190 191 192 193 194 195
    return im


def plot_tracking_dict(image,
                       num_classes,
                       tlwhs_dict,
                       obj_ids_dict,
                       scores_dict,
                       frame_id=0,
                       fps=0.,
196
                       ids2names=[],
197
                       do_entrance_counting=False,
198
                       do_break_in_counting=False,
199 200
                       do_illegal_parking_recognition=False,
                       illegal_parking_dict=None,
W
wangguanzhong 已提交
201 202 203
                       entrance=None,
                       records=None,
                       center_traj=None):
204 205
    im = np.ascontiguousarray(np.copy(image))
    im_h, im_w = im.shape[:2]
206
    if do_break_in_counting or do_illegal_parking_recognition:
207
        entrance = np.array(entrance[:-1])  # last pair is [im_w, im_h]
208

W
wangguanzhong 已提交
209
    text_scale = max(0.5, image.shape[1] / 3000.)
210 211 212
    text_thickness = 2
    line_thickness = max(1, int(image.shape[1] / 500.))

W
wangguanzhong 已提交
213
    if num_classes == 1:
F
Feng Ni 已提交
214 215 216 217 218
        if records is not None:
            start = records[-1].find('Total')
            end = records[-1].find('In')
            cv2.putText(
                im,
219
                records[-1][start:end], (0, int(40 * text_scale) + 10),
W
wangguanzhong 已提交
220
                cv2.FONT_ITALIC,
F
Feng Ni 已提交
221
                text_scale, (0, 0, 255),
W
wangguanzhong 已提交
222
                thickness=text_thickness)
W
wangguanzhong 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235

    if num_classes == 1 and do_entrance_counting:
        entrance_line = tuple(map(int, entrance))
        cv2.rectangle(
            im,
            entrance_line[0:2],
            entrance_line[2:4],
            color=(0, 255, 255),
            thickness=line_thickness)
        # find start location for entrance counting data
        start = records[-1].find('In')
        cv2.putText(
            im,
236
            records[-1][start:-1], (0, int(60 * text_scale) + 10),
W
wangguanzhong 已提交
237
            cv2.FONT_ITALIC,
W
wangguanzhong 已提交
238
            text_scale, (0, 0, 255),
W
wangguanzhong 已提交
239
            thickness=text_thickness)
W
wangguanzhong 已提交
240

241 242
    if num_classes == 1 and (do_break_in_counting or
                             do_illegal_parking_recognition):
243 244 245 246 247 248 249 250 251 252 253 254 255 256
        np_masks = np.zeros((im_h, im_w, 1), np.uint8)
        cv2.fillPoly(np_masks, [entrance], 255)

        # Draw region mask
        alpha = 0.3
        im = np.array(im).astype('float32')
        mask = np_masks[:, :, 0]
        color_mask = [0, 0, 255]
        idx = np.nonzero(mask)
        color_mask = np.array(color_mask)
        im[idx[0], idx[1], :] *= 1.0 - alpha
        im[idx[0], idx[1], :] += alpha * color_mask
        im = np.array(im).astype('uint8')

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
        if do_break_in_counting:
            # find start location for break in counting data
            start = records[-1].find('Break_in')
            cv2.putText(
                im,
                records[-1][start:-1],
                (entrance[0][0] - 10, entrance[0][1] - 10),
                cv2.FONT_ITALIC,
                text_scale, (0, 0, 255),
                thickness=text_thickness)

        if illegal_parking_dict is not None and len(illegal_parking_dict) != 0:
            for key, value in illegal_parking_dict.items():
                x1, y1, w, h = value['bbox']
                plate = value['plate']
272 273
                if plate is None:
                    plate = ""
274 275 276 277 278 279 280 281 282 283 284 285

                # red box
                cv2.rectangle(im, (int(x1), int(y1)),
                              (int(x1 + w), int(y1 + h)), (0, 0, 255), 2)

                cv2.putText(
                    im,
                    "illegal_parking:" + plate,
                    (int(x1) + 5, int(16 * text_scale + y1 + 15)),
                    cv2.FONT_ITALIC,
                    text_scale * 1.5, (0, 0, 255),
                    thickness=text_thickness)
286

287 288 289 290 291 292 293
    for cls_id in range(num_classes):
        tlwhs = tlwhs_dict[cls_id]
        obj_ids = obj_ids_dict[cls_id]
        scores = scores_dict[cls_id]
        cv2.putText(
            im,
            'frame: %d fps: %.2f num: %d' % (frame_id, fps, len(tlwhs)),
W
wangguanzhong 已提交
294 295
            (0, int(15 * text_scale) + 5),
            cv2.FONT_ITALIC,
296
            text_scale, (0, 0, 255),
W
wangguanzhong 已提交
297
            thickness=text_thickness)
298

W
wangguanzhong 已提交
299
        record_id = set()
300 301 302
        for i, tlwh in enumerate(tlwhs):
            x1, y1, w, h = tlwh
            intbox = tuple(map(int, (x1, y1, x1 + w, y1 + h)))
W
wangguanzhong 已提交
303
            center = tuple(map(int, (x1 + w / 2., y1 + h / 2.)))
304
            obj_id = int(obj_ids[i])
W
wangguanzhong 已提交
305 306
            if center_traj is not None:
                record_id.add(obj_id)
W
wangguanzhong 已提交
307 308 309
                if obj_id not in center_traj[cls_id]:
                    center_traj[cls_id][obj_id] = deque(maxlen=30)
                center_traj[cls_id][obj_id].append(center)
310 311 312 313 314 315 316 317

            id_text = '{}'.format(int(obj_id))
            if ids2names != []:
                id_text = '{}_{}'.format(ids2names[cls_id], id_text)
            else:
                id_text = 'class{}_{}'.format(cls_id, id_text)

            _line_thickness = 1 if obj_id <= 0 else line_thickness
318 319 320 321 322 323 324 325 326 327 328

            in_region = False
            if do_break_in_counting:
                center_x = min(x1 + w / 2., im_w - 1)
                center_down_y = min(y1 + h, im_h - 1)
                if in_quadrangle([center_x, center_down_y], entrance, im_h,
                                 im_w):
                    in_region = True

            color = get_color(abs(obj_id)) if in_region == False else (0, 0,
                                                                       255)
329 330 331 332 333 334 335 336
            cv2.rectangle(
                im,
                intbox[0:2],
                intbox[2:4],
                color=color,
                thickness=line_thickness)
            cv2.putText(
                im,
W
wangguanzhong 已提交
337 338
                id_text, (intbox[0], intbox[1] - 25),
                cv2.FONT_ITALIC,
339 340
                text_scale,
                color,
341 342
                thickness=text_thickness)

343 344 345 346 347 348 349 350
            if do_break_in_counting and in_region:
                cv2.putText(
                    im,
                    'Break in now.', (intbox[0], intbox[1] - 50),
                    cv2.FONT_ITALIC,
                    text_scale, (0, 0, 255),
                    thickness=text_thickness)

351
            if scores is not None:
W
wangguanzhong 已提交
352
                text = 'score: {:.2f}'.format(float(scores[i]))
353 354
                cv2.putText(
                    im,
W
wangguanzhong 已提交
355 356
                    text, (intbox[0], intbox[1] - 6),
                    cv2.FONT_ITALIC,
357 358
                    text_scale,
                    color,
359
                    thickness=text_thickness)
W
wangguanzhong 已提交
360 361 362 363 364 365 366
        if center_traj is not None:
            for traj in center_traj:
                for i in traj.keys():
                    if i not in record_id:
                        continue
                    for point in traj[i]:
                        cv2.circle(im, point, 3, (0, 0, 255), -1)
367
    return im
368 369 370 371 372 373 374 375 376 377


def in_quadrangle(point, entrance, im_h, im_w):
    mask = np.zeros((im_h, im_w, 1), np.uint8)
    cv2.fillPoly(mask, [entrance], 255)
    p = tuple(map(int, point))
    if mask[p[1], p[0], :] > 0:
        return True
    else:
        return False