utils.py 8.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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.

import os
import cv2
import time
import numpy as np
F
Feng Ni 已提交
19
from .visualization import plot_tracking_dict, plot_tracking
20 21

__all__ = [
22
    'MOTTimer',
23
    'Detection',
24 25
    'write_mot_results',
    'save_vis_results',
26 27 28 29 30 31 32 33
    'load_det_results',
    'preprocess_reid',
    'get_crops',
    'clip_box',
    'scale_coords',
]


34
class MOTTimer(object):
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
    """
    This class used to compute and print the current FPS while evaling.
    """

    def __init__(self):
        self.total_time = 0.
        self.calls = 0
        self.start_time = 0.
        self.diff = 0.
        self.average_time = 0.
        self.duration = 0.

    def tic(self):
        # using time.time instead of time.clock because time time.clock
        # does not normalize for multithreading
        self.start_time = time.time()

    def toc(self, average=True):
        self.diff = time.time() - self.start_time
        self.total_time += self.diff
        self.calls += 1
        self.average_time = self.total_time / self.calls
        if average:
            self.duration = self.average_time
        else:
            self.duration = self.diff
        return self.duration

    def clear(self):
        self.total_time = 0.
        self.calls = 0
        self.start_time = 0.
        self.diff = 0.
        self.average_time = 0.
        self.duration = 0.


class Detection(object):
    """
    This class represents a bounding box detection in a single image.

    Args:
77
        tlwh (Tensor): Bounding box in format `(top left x, top left y,
78
            width, height)`.
79
        score (Tensor): Bounding box confidence score.
80 81
        feature (Tensor): A feature vector that describes the object 
            contained in this image.
82
        cls_id (Tensor): Bounding box category id.
83 84
    """

85
    def __init__(self, tlwh, score, feature, cls_id):
86
        self.tlwh = np.asarray(tlwh, dtype=np.float32)
87 88 89
        self.score = float(score)
        self.feature = np.asarray(feature, dtype=np.float32)
        self.cls_id = int(cls_id)
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

    def to_tlbr(self):
        """
        Convert bounding box to format `(min x, min y, max x, max y)`, i.e.,
        `(top left, bottom right)`.
        """
        ret = self.tlwh.copy()
        ret[2:] += ret[:2]
        return ret

    def to_xyah(self):
        """
        Convert bounding box to format `(center x, center y, aspect ratio,
        height)`, where the aspect ratio is `width / height`.
        """
        ret = self.tlwh.copy()
        ret[:2] += ret[2:] / 2
        ret[2] /= ret[3]
        return ret


111 112 113 114 115 116 117 118 119 120 121 122
def write_mot_results(filename, results, data_type='mot', num_classes=1):
    # support single and multi classes
    if data_type in ['mot', 'mcmot']:
        save_format = '{frame},{id},{x1},{y1},{w},{h},{score},{cls_id},-1,-1\n'
    elif data_type == 'kitti':
        save_format = '{frame} {id} car 0 0 -10 {x1} {y1} {x2} {y2} -10 -10 -10 -1000 -1000 -1000 -10\n'
    else:
        raise ValueError(data_type)

    f = open(filename, 'w')
    for cls_id in range(num_classes):
        for frame_id, tlwhs, tscores, track_ids in results[cls_id]:
123 124
            if data_type == 'kitti':
                frame_id -= 1
125 126
            for tlwh, score, track_id in zip(tlwhs, tscores, track_ids):
                if track_id < 0: continue
127
                if data_type == 'mot':
128 129 130
                    cls_id = -1

                x1, y1, w, h = tlwh
131
                x2, y2 = x1 + w, y1 + h
132 133 134 135 136
                line = save_format.format(
                    frame=frame_id,
                    id=track_id,
                    x1=x1,
                    y1=y1,
137 138
                    x2=x2,
                    y2=y2,
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
                    w=w,
                    h=h,
                    score=score,
                    cls_id=cls_id)
                f.write(line)
    print('MOT results save in {}'.format(filename))


def save_vis_results(data,
                     frame_id,
                     online_ids,
                     online_tlwhs,
                     online_scores,
                     average_time,
                     show_image,
                     save_dir,
155 156
                     num_classes=1,
                     ids2names=[]):
157 158 159
    if show_image or save_dir is not None:
        assert 'ori_image' in data
        img0 = data['ori_image'].numpy()[0]
F
Feng Ni 已提交
160 161 162 163 164 165 166 167 168 169 170
        if online_ids is None:
            online_im = img0
        else:
            if isinstance(online_tlwhs, dict):
                online_im = plot_tracking_dict(
                    img0,
                    num_classes,
                    online_tlwhs,
                    online_ids,
                    online_scores,
                    frame_id=frame_id,
171 172
                    fps=1. / average_time,
                    ids2names=ids2names)
F
Feng Ni 已提交
173 174 175 176 177 178 179
            else:
                online_im = plot_tracking(
                    img0,
                    online_tlwhs,
                    online_ids,
                    online_scores,
                    frame_id=frame_id,
180 181
                    fps=1. / average_time,
                    ids2names=ids2names)
182 183 184 185 186 187 188
    if show_image:
        cv2.imshow('online_im', online_im)
    if save_dir is not None:
        cv2.imwrite(
            os.path.join(save_dir, '{:05d}.jpg'.format(frame_id)), online_im)


189 190
def load_det_results(det_file, num_frames):
    assert os.path.exists(det_file) and os.path.isfile(det_file), \
191
        '{} is not exist or not a file.'.format(det_file)
192
    labels = np.loadtxt(det_file, dtype='float32', delimiter=',')
193 194
    assert labels.shape[1] == 7, \
        "Each line of {} should have 7 items: '[frame_id],[x0],[y0],[w],[h],[score],[class_id]'.".format(det_file)
195
    results_list = []
196 197
    for frame_i in range(num_frames):
        results = {'bbox': [], 'score': [], 'cls_id': []}
198
        lables_with_frame = labels[labels[:, 0] == frame_i + 1]
199 200
        # each line of lables_with_frame:
        # [frame_id],[x0],[y0],[w],[h],[score],[class_id]
201
        for l in lables_with_frame:
202
            results['bbox'].append(l[1:5])
F
Feng Ni 已提交
203 204
            results['score'].append(l[5:6])
            results['cls_id'].append(l[6:7])
205 206 207 208 209
        results_list.append(results)
    return results_list


def scale_coords(coords, input_shape, im_shape, scale_factor):
F
Feng Ni 已提交
210 211 212 213 214 215 216
    # Note: ratio has only one value, scale_factor[0] == scale_factor[1]
    # 
    # This function only used for JDE YOLOv3 or other detectors with 
    # LetterBoxResize and JDEBBoxPostProcess, coords output from detector had
    # not scaled back to the origin image.

    ratio = scale_factor[0]
217 218
    pad_w = (input_shape[1] - int(im_shape[1])) / 2
    pad_h = (input_shape[0] - int(im_shape[0])) / 2
219 220
    coords[:, 0::2] -= pad_w
    coords[:, 1::2] -= pad_h
221
    coords[:, 0:4] /= ratio
F
Feng Ni 已提交
222
    coords[:, :4] = np.clip(coords[:, :4], a_min=0, a_max=coords[:, :4].max())
223 224 225
    return coords.round()


F
Feng Ni 已提交
226 227 228 229
def clip_box(xyxy, ori_image_shape):
    H, W = ori_image_shape
    xyxy[:, 0::2] = np.clip(xyxy[:, 0::2], a_min=0, a_max=W)
    xyxy[:, 1::2] = np.clip(xyxy[:, 1::2], a_min=0, a_max=H)
230 231
    w = xyxy[:, 2:3] - xyxy[:, 0:1]
    h = xyxy[:, 3:4] - xyxy[:, 1:2]
F
Feng Ni 已提交
232 233 234
    mask = np.logical_and(h > 0, w > 0)
    keep_idx = np.nonzero(mask)
    return xyxy[keep_idx[0]], keep_idx
235 236


237
def get_crops(xyxy, ori_img, w, h):
238
    crops = []
F
Feng Ni 已提交
239
    xyxy = xyxy.astype(np.int64)
240
    ori_img = ori_img.numpy()
F
Feng Ni 已提交
241
    ori_img = np.squeeze(ori_img, axis=0).transpose(1, 0, 2)  # [h,w,3]->[w,h,3]
242 243 244 245
    for i, bbox in enumerate(xyxy):
        crop = ori_img[bbox[0]:bbox[2], bbox[1]:bbox[3], :]
        crops.append(crop)
    crops = preprocess_reid(crops, w, h)
246
    return crops
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265


def preprocess_reid(imgs,
                    w=64,
                    h=192,
                    mean=[0.485, 0.456, 0.406],
                    std=[0.229, 0.224, 0.225]):
    im_batch = []
    for img in imgs:
        img = cv2.resize(img, (w, h))
        img = img[:, :, ::-1].astype('float32').transpose((2, 0, 1)) / 255
        img_mean = np.array(mean).reshape((3, 1, 1))
        img_std = np.array(std).reshape((3, 1, 1))
        img -= img_mean
        img /= img_std
        img = np.expand_dims(img, axis=0)
        im_batch.append(img)
    im_batch = np.concatenate(im_batch, 0)
    return im_batch