Skip to content

Commit

Permalink
Fix mot lazy import and warning (#6476)
Browse files Browse the repository at this point in the history
* [Dy2St]Fix cascade_rcnn export model problem (#6468)

* [Dy2St]Fix cascade_rcnn export model problem

* [Dy2St]Fix cascade_rcnn export model problem

* fix import for mot

* fix import for mot deploy

* fix lazy import mot
  • Loading branch information
nemonameless authored Jul 20, 2022
1 parent 0e2e892 commit 714b339
Show file tree
Hide file tree
Showing 15 changed files with 156 additions and 41 deletions.
2 changes: 1 addition & 1 deletion configs/mot/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ PP-Human赋能社区智能精细化管理教程[链接](https://aistudio.baidu.c
```
pip install -r requirements.txt
# 或手动pip安装MOT相关的库
pip install lap sklearn motmetrics openpyxl
pip install lap motmetrics sklearn filterpy
```
**注意:**
- 预测需确保已安装[ffmpeg](https://ffmpeg.org/ffmpeg.html), Linux(Ubuntu)平台可以直接用以下命令安装:`apt-get update && apt-get install -y ffmpeg`
Expand Down
2 changes: 1 addition & 1 deletion configs/mot/README_en.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ PP-Tracking supports GUI predict and deployment. Please refer to this [doc](http
## Installation
Install all the related dependencies for MOT:
```
pip install lap sklearn motmetrics openpyxl
pip install lap motmetrics sklearn filterpy
or
pip install -r requirements.txt
```
Expand Down
10 changes: 8 additions & 2 deletions deploy/pipeline/pphuman/mtmct.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,14 @@
import cv2
import gc
import numpy as np
from sklearn import preprocessing
from sklearn.cluster import AgglomerativeClustering
try:
from sklearn import preprocessing
from sklearn.cluster import AgglomerativeClustering
except:
print(
'Warning: Unable to use MTMCT in PP-Human, please install sklearn, for example: `pip install sklearn`'
)
pass
import pandas as pd
from tqdm import tqdm
from functools import reduce
Expand Down
7 changes: 6 additions & 1 deletion deploy/pipeline/ppvehicle/vehicleplate_postprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
from paddle.nn import functional as F
import re
from shapely.geometry import Polygon
import pyclipper
import cv2
import copy

Expand Down Expand Up @@ -111,6 +110,12 @@ def boxes_from_bitmap(self, pred, _bitmap, dest_width, dest_height):
return np.array(boxes, dtype=np.int16), scores

def unclip(self, box):
try:
import pyclipper
except Exception as e:
raise RuntimeError(
'Unable to use vehicleplate postprocess in PP-Vehicle, please install pyclipper, for example: `pip install pyclipper`, see https://github.com/fonttools/pyclipper'
)
unclip_ratio = self.unclip_ratio
poly = Polygon(box)
distance = poly.area * unclip_ratio / poly.length
Expand Down
15 changes: 14 additions & 1 deletion deploy/pptracking/python/mot/matching/jde_matching.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,14 @@
This code is based on https://github.com/Zhongdao/Towards-Realtime-MOT/blob/master/tracker/matching.py
"""

import lap
try:
import lap
except:
print(
'Warning: Unable to use JDE/FairMOT/ByteTrack, please install lap, for example: `pip install lap`, see https://github.com/gatagat/lap'
)
pass

import scipy
import numpy as np
from scipy.spatial.distance import cdist
Expand Down Expand Up @@ -53,6 +60,12 @@ def merge_matches(m1, m2, shape):


def linear_assignment(cost_matrix, thresh):
try:
import lap
except Exception as e:
raise RuntimeError(
'Unable to use JDE/FairMOT/ByteTrack, please install lap, for example: `pip install lap`, see https://github.com/gatagat/lap'
)
if cost_matrix.size == 0:
return np.empty(
(0, 2), dtype=int), tuple(range(cost_matrix.shape[0])), tuple(
Expand Down
8 changes: 7 additions & 1 deletion deploy/pptracking/python/mot/mtmct/camera_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,13 @@
"""

import numpy as np
from sklearn.cluster import AgglomerativeClustering
try:
from sklearn.cluster import AgglomerativeClustering
except:
print(
'Warning: Unable to use MTMCT in PP-Tracking, please install sklearn, for example: `pip install sklearn`'
)
pass
from .utils import get_dire, get_match, get_cid_tid, combin_feature, combin_cluster
from .utils import normalize, intracam_ignore, visual_rerank

Expand Down
14 changes: 13 additions & 1 deletion deploy/pptracking/python/mot/mtmct/postprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,13 @@
import cv2
from tqdm import tqdm
import numpy as np
import motmetrics as mm
try:
import motmetrics as mm
except:
print(
'Warning: Unable to use motmetrics in MTMCT in PP-Tracking, please install motmetrics, for example: `pip install motmetrics`, see https://github.com/longcw/py-motmetrics'
)
pass
from functools import reduce

from .utils import parse_pt_gt, parse_pt, compare_dataframes_mtmc
Expand Down Expand Up @@ -201,6 +207,12 @@ def print_mtmct_result(gt_file, pred_file):
summary.loc[:, 'idr'] *= 100
summary.loc[:, 'idf1'] *= 100
summary.loc[:, 'mota'] *= 100
try:
import motmetrics as mm
except Exception as e:
raise RuntimeError(
'Unable to use motmetrics in MTMCT in PP-Tracking, please install motmetrics, for example: `pip install motmetrics`, see https://github.com/longcw/py-motmetrics'
)
print(
mm.io.render_summary(
summary,
Expand Down
30 changes: 23 additions & 7 deletions deploy/pptracking/python/mot/mtmct/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,6 @@
import cv2
import gc
import numpy as np
from sklearn import preprocessing
from sklearn.cluster import AgglomerativeClustering
import motmetrics as mm
import pandas as pd
from tqdm import tqdm
import warnings
Expand Down Expand Up @@ -195,10 +192,10 @@ def find_topk(a, k, axis=-1, largest=True, sorted=True):

a = np.asanyarray(a)
if largest:
index_array = np.argpartition(a, axis_size-k, axis=axis)
topk_indices = np.take(index_array, -np.arange(k)-1, axis=axis)
index_array = np.argpartition(a, axis_size - k, axis=axis)
topk_indices = np.take(index_array, -np.arange(k) - 1, axis=axis)
else:
index_array = np.argpartition(a, k-1, axis=axis)
index_array = np.argpartition(a, k - 1, axis=axis)
topk_indices = np.take(index_array, np.arange(k), axis=axis)
topk_values = np.take_along_axis(a, topk_indices, axis=axis)
if sorted:
Expand Down Expand Up @@ -228,7 +225,8 @@ def batch_numpy_topk(qf, gf, k1, N=6000):
temp_qd = temp_qd / (np.max(temp_qd, axis=0)[0])
temp_qd = temp_qd.T
initial_rank.append(
find_topk(temp_qd, k=k1, axis=1, largest=False, sorted=True)[1])
find_topk(
temp_qd, k=k1, axis=1, largest=False, sorted=True)[1])
del temp_qd
del temp_gf
del temp_qf
Expand Down Expand Up @@ -374,6 +372,12 @@ def visual_rerank(prb_feats,


def normalize(nparray, axis=0):
try:
from sklearn import preprocessing
except Exception as e:
raise RuntimeError(
'Unable to use sklearn in MTMCT in PP-Tracking, please install sklearn, for example: `pip install sklearn`'
)
nparray = preprocessing.normalize(nparray, norm='l2', axis=axis)
return nparray

Expand Down Expand Up @@ -453,6 +457,12 @@ def parse_pt_gt(mot_feature):

# eval result
def compare_dataframes_mtmc(gts, ts):
try:
import motmetrics as mm
except Exception as e:
raise RuntimeError(
'Unable to use motmetrics in MTMCT in PP-Tracking, please install motmetrics, for example: `pip install motmetrics`, see https://github.com/longcw/py-motmetrics'
)
"""Compute ID-based evaluation metrics for MTMCT
Return:
df (pandas.DataFrame): Results of the evaluations in a df with only the 'idf1', 'idp', and 'idr' columns.
Expand Down Expand Up @@ -528,6 +538,12 @@ def get_labels(cid_tid_dict,
use_ff=True,
use_rerank=True,
use_st_filter=False):
try:
from sklearn.cluster import AgglomerativeClustering
except Exception as e:
raise RuntimeError(
'Unable to use sklearn in MTMCT in PP-Tracking, please install sklearn, for example: `pip install sklearn`'
)
# 1st cluster
sim_matrix = get_sim_matrix(
cid_tid_dict,
Expand Down
8 changes: 7 additions & 1 deletion deploy/pptracking/python/mot/mtmct/zone.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,13 @@
import os
import cv2
import numpy as np
from sklearn.cluster import AgglomerativeClustering
try:
from sklearn.cluster import AgglomerativeClustering
except:
print(
'Warning: Unable to use MTMCT in PP-Tracking, please install sklearn, for example: `pip install sklearn`'
)
pass

BBOX_B = 10 / 15

Expand Down
14 changes: 13 additions & 1 deletion deploy/pptracking/python/mot/tracker/ocsort_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,13 @@
"""

import numpy as np
from filterpy.kalman import KalmanFilter
try:
from filterpy.kalman import KalmanFilter
except:
print(
'Warning: Unable to use OC-SORT, please install filterpy, for example: `pip install filterpy`, see https://github.com/rlabbe/filterpy'
)
pass

from ..matching.ocsort_matching import associate, linear_assignment, iou_batch

Expand Down Expand Up @@ -84,6 +90,12 @@ class KalmanBoxTracker(object):
count = 0

def __init__(self, bbox, delta_t=3):
try:
from filterpy.kalman import KalmanFilter
except Exception as e:
raise RuntimeError(
'Unable to use OC-SORT, please install filterpy, for example: `pip install filterpy`, see https://github.com/rlabbe/filterpy'
)
self.kf = KalmanFilter(dim_x=7, dim_z=4)
self.kf.F = np.array([[1, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0, 1], [0, 0, 0, 1, 0, 0, 0],
Expand Down
29 changes: 17 additions & 12 deletions ppdet/metrics/mcmot_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,21 @@
import sys
import math
from collections import defaultdict
from motmetrics.math_util import quiet_divide

import numpy as np
import pandas as pd

from .metrics import Metric
import motmetrics as mm
import openpyxl
metrics = mm.metrics.motchallenge_metrics
mh = mm.metrics.create()
try:
import motmetrics as mm
from motmetrics.math_util import quiet_divide
metrics = mm.metrics.motchallenge_metrics
mh = mm.metrics.create()
except:
print(
'Warning: Unable to use MCMOT metric, please install motmetrics, for example: `pip install motmetrics`, see https://github.com/longcw/py-motmetrics'
)
pass
from ppdet.utils.logger import setup_logger
logger = setup_logger(__name__)

Expand Down Expand Up @@ -300,6 +305,13 @@ def __init__(self, data_root, seq_name, data_type, num_classes):
self.num_classes = num_classes

self.load_annotations()
try:
import motmetrics as mm
mm.lap.default_solver = 'lap'
except Exception as e:
raise RuntimeError(
'Unable to use MCMOT metric, please install motmetrics, for example: `pip install motmetrics`, see https://github.com/longcw/py-motmetrics'
)
self.reset_accumulator()

self.class_accs = []
Expand All @@ -314,13 +326,9 @@ def load_annotations(self):
)

def reset_accumulator(self):
import motmetrics as mm
mm.lap.default_solver = 'lap'
self.acc = mm.MOTAccumulator(auto_id=True)

def eval_frame_dict(self, trk_objs, gt_objs, rtn_events=False, union=False):
import motmetrics as mm
mm.lap.default_solver = 'lap'
if union:
trk_tlwhs, trk_ids, trk_cls = unzip_objs_cls(trk_objs)[:3]
gt_tlwhs, gt_ids, gt_cls = unzip_objs_cls(gt_objs)[:3]
Expand Down Expand Up @@ -394,9 +402,6 @@ def get_summary(accs,
names,
metrics=('mota', 'num_switches', 'idp', 'idr', 'idf1',
'precision', 'recall')):
import motmetrics as mm
mm.lap.default_solver = 'lap'

names = copy.deepcopy(names)
if metrics is None:
metrics = mm.metrics.motchallenge_metrics
Expand Down
24 changes: 16 additions & 8 deletions ppdet/metrics/mot_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@
from .metrics import Metric
from .munkres import Munkres

try:
import motmetrics as mm
mm.lap.default_solver = 'lap'
except:
print(
'Warning: Unable to use MOT metric, please install motmetrics, for example: `pip install motmetrics`, see https://github.com/longcw/py-motmetrics'
)
pass

from ppdet.utils.logger import setup_logger
logger = setup_logger(__name__)

Expand Down Expand Up @@ -114,6 +123,13 @@ def __init__(self, data_root, seq_name, data_type):
self.data_type = data_type

self.load_annotations()
try:
import motmetrics as mm
mm.lap.default_solver = 'lap'
except Exception as e:
raise RuntimeError(
'Unable to use MOT metric, please install motmetrics, for example: `pip install motmetrics`, see https://github.com/longcw/py-motmetrics'
)
self.reset_accumulator()

def load_annotations(self):
Expand All @@ -129,13 +145,9 @@ def load_annotations(self):
gt_filename, is_ignore=True)

def reset_accumulator(self):
import motmetrics as mm
mm.lap.default_solver = 'lap'
self.acc = mm.MOTAccumulator(auto_id=True)

def eval_frame(self, frame_id, trk_tlwhs, trk_ids, rtn_events=False):
import motmetrics as mm
mm.lap.default_solver = 'lap'
# results
trk_tlwhs = np.copy(trk_tlwhs)
trk_ids = np.copy(trk_ids)
Expand Down Expand Up @@ -193,8 +205,6 @@ def get_summary(accs,
names,
metrics=('mota', 'num_switches', 'idp', 'idr', 'idf1',
'precision', 'recall')):
import motmetrics as mm
mm.lap.default_solver = 'lap'
names = copy.deepcopy(names)
if metrics is None:
metrics = mm.metrics.motchallenge_metrics
Expand Down Expand Up @@ -231,8 +241,6 @@ def update(self, data_root, seq, data_type, result_root, result_filename):
self.result_root = result_root

def accumulate(self):
import motmetrics as mm
import openpyxl
metrics = mm.metrics.motchallenge_metrics
mh = mm.metrics.create()
summary = self.MOTEvaluator.get_summary(self.accs, self.seqs, metrics)
Expand Down
15 changes: 14 additions & 1 deletion ppdet/modeling/mot/matching/jde_matching.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,14 @@
This code is based on https://github.com/Zhongdao/Towards-Realtime-MOT/blob/master/tracker/matching.py
"""

import lap
try:
import lap
except:
print(
'Warning: Unable to use JDE/FairMOT/ByteTrack, please install lap, for example: `pip install lap`, see https://github.com/gatagat/lap'
)
pass

import scipy
import numpy as np
from scipy.spatial.distance import cdist
Expand Down Expand Up @@ -53,6 +60,12 @@ def merge_matches(m1, m2, shape):


def linear_assignment(cost_matrix, thresh):
try:
import lap
except Exception as e:
raise RuntimeError(
'Unable to use JDE/FairMOT/ByteTrack, please install lap, for example: `pip install lap`, see https://github.com/gatagat/lap'
)
if cost_matrix.size == 0:
return np.empty(
(0, 2), dtype=int), tuple(range(cost_matrix.shape[0])), tuple(
Expand Down
Loading

0 comments on commit 714b339

Please sign in to comment.