Spaces:
Paused
Paused
Upload 4 files
Browse files- recognition/arcface_onnx.py +91 -0
- recognition/face_align.py +141 -0
- recognition/main.py +57 -0
- recognition/scrfd.py +329 -0
recognition/arcface_onnx.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# @Organization : insightface.ai
|
| 3 |
+
# @Author : Jia Guo
|
| 4 |
+
# @Time : 2021-05-04
|
| 5 |
+
# @Function :
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import cv2
|
| 9 |
+
import onnx
|
| 10 |
+
import onnxruntime
|
| 11 |
+
import face_align
|
| 12 |
+
|
| 13 |
+
__all__ = [
|
| 14 |
+
'ArcFaceONNX',
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class ArcFaceONNX:
|
| 19 |
+
def __init__(self, model_file=None, session=None):
|
| 20 |
+
assert model_file is not None
|
| 21 |
+
self.model_file = model_file
|
| 22 |
+
self.session = session
|
| 23 |
+
self.taskname = 'recognition'
|
| 24 |
+
find_sub = False
|
| 25 |
+
find_mul = False
|
| 26 |
+
model = onnx.load(self.model_file)
|
| 27 |
+
graph = model.graph
|
| 28 |
+
for nid, node in enumerate(graph.node[:8]):
|
| 29 |
+
#print(nid, node.name)
|
| 30 |
+
if node.name.startswith('Sub') or node.name.startswith('_minus'):
|
| 31 |
+
find_sub = True
|
| 32 |
+
if node.name.startswith('Mul') or node.name.startswith('_mul'):
|
| 33 |
+
find_mul = True
|
| 34 |
+
if find_sub and find_mul:
|
| 35 |
+
#mxnet arcface model
|
| 36 |
+
input_mean = 0.0
|
| 37 |
+
input_std = 1.0
|
| 38 |
+
else:
|
| 39 |
+
input_mean = 127.5
|
| 40 |
+
input_std = 127.5
|
| 41 |
+
self.input_mean = input_mean
|
| 42 |
+
self.input_std = input_std
|
| 43 |
+
#print('input mean and std:', self.input_mean, self.input_std)
|
| 44 |
+
if self.session is None:
|
| 45 |
+
self.session = onnxruntime.InferenceSession(self.model_file, providers=['CoreMLExecutionProvider','CUDAExecutionProvider'])
|
| 46 |
+
input_cfg = self.session.get_inputs()[0]
|
| 47 |
+
input_shape = input_cfg.shape
|
| 48 |
+
input_name = input_cfg.name
|
| 49 |
+
self.input_size = tuple(input_shape[2:4][::-1])
|
| 50 |
+
self.input_shape = input_shape
|
| 51 |
+
outputs = self.session.get_outputs()
|
| 52 |
+
output_names = []
|
| 53 |
+
for out in outputs:
|
| 54 |
+
output_names.append(out.name)
|
| 55 |
+
self.input_name = input_name
|
| 56 |
+
self.output_names = output_names
|
| 57 |
+
assert len(self.output_names)==1
|
| 58 |
+
self.output_shape = outputs[0].shape
|
| 59 |
+
|
| 60 |
+
def prepare(self, ctx_id, **kwargs):
|
| 61 |
+
if ctx_id<0:
|
| 62 |
+
self.session.set_providers(['CPUExecutionProvider'])
|
| 63 |
+
|
| 64 |
+
def get(self, img, kps):
|
| 65 |
+
aimg = face_align.norm_crop(img, landmark=kps, image_size=self.input_size[0])
|
| 66 |
+
embedding = self.get_feat(aimg).flatten()
|
| 67 |
+
return embedding
|
| 68 |
+
|
| 69 |
+
def compute_sim(self, feat1, feat2):
|
| 70 |
+
from numpy.linalg import norm
|
| 71 |
+
feat1 = feat1.ravel()
|
| 72 |
+
feat2 = feat2.ravel()
|
| 73 |
+
sim = np.dot(feat1, feat2) / (norm(feat1) * norm(feat2))
|
| 74 |
+
return sim
|
| 75 |
+
|
| 76 |
+
def get_feat(self, imgs):
|
| 77 |
+
if not isinstance(imgs, list):
|
| 78 |
+
imgs = [imgs]
|
| 79 |
+
input_size = self.input_size
|
| 80 |
+
|
| 81 |
+
blob = cv2.dnn.blobFromImages(imgs, 1.0 / self.input_std, input_size,
|
| 82 |
+
(self.input_mean, self.input_mean, self.input_mean), swapRB=True)
|
| 83 |
+
net_out = self.session.run(self.output_names, {self.input_name: blob})[0]
|
| 84 |
+
return net_out
|
| 85 |
+
|
| 86 |
+
def forward(self, batch_data):
|
| 87 |
+
blob = (batch_data - self.input_mean) / self.input_std
|
| 88 |
+
net_out = self.session.run(self.output_names, {self.input_name: blob})[0]
|
| 89 |
+
return net_out
|
| 90 |
+
|
| 91 |
+
|
recognition/face_align.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import numpy as np
|
| 3 |
+
from skimage import transform as trans
|
| 4 |
+
|
| 5 |
+
src1 = np.array([[51.642, 50.115], [57.617, 49.990], [35.740, 69.007],
|
| 6 |
+
[51.157, 89.050], [57.025, 89.702]],
|
| 7 |
+
dtype=np.float32)
|
| 8 |
+
#<--left
|
| 9 |
+
src2 = np.array([[45.031, 50.118], [65.568, 50.872], [39.677, 68.111],
|
| 10 |
+
[45.177, 86.190], [64.246, 86.758]],
|
| 11 |
+
dtype=np.float32)
|
| 12 |
+
|
| 13 |
+
#---frontal
|
| 14 |
+
src3 = np.array([[39.730, 51.138], [72.270, 51.138], [56.000, 68.493],
|
| 15 |
+
[42.463, 87.010], [69.537, 87.010]],
|
| 16 |
+
dtype=np.float32)
|
| 17 |
+
|
| 18 |
+
#-->right
|
| 19 |
+
src4 = np.array([[46.845, 50.872], [67.382, 50.118], [72.737, 68.111],
|
| 20 |
+
[48.167, 86.758], [67.236, 86.190]],
|
| 21 |
+
dtype=np.float32)
|
| 22 |
+
|
| 23 |
+
#-->right profile
|
| 24 |
+
src5 = np.array([[54.796, 49.990], [60.771, 50.115], [76.673, 69.007],
|
| 25 |
+
[55.388, 89.702], [61.257, 89.050]],
|
| 26 |
+
dtype=np.float32)
|
| 27 |
+
|
| 28 |
+
src = np.array([src1, src2, src3, src4, src5])
|
| 29 |
+
src_map = {112: src, 224: src * 2}
|
| 30 |
+
|
| 31 |
+
arcface_src = np.array(
|
| 32 |
+
[[38.2946, 51.6963], [73.5318, 51.5014], [56.0252, 71.7366],
|
| 33 |
+
[41.5493, 92.3655], [70.7299, 92.2041]],
|
| 34 |
+
dtype=np.float32)
|
| 35 |
+
|
| 36 |
+
arcface_src = np.expand_dims(arcface_src, axis=0)
|
| 37 |
+
|
| 38 |
+
# In[66]:
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# lmk is prediction; src is template
|
| 42 |
+
def estimate_norm(lmk, image_size=112, mode='arcface'):
|
| 43 |
+
assert lmk.shape == (5, 2)
|
| 44 |
+
tform = trans.SimilarityTransform()
|
| 45 |
+
lmk_tran = np.insert(lmk, 2, values=np.ones(5), axis=1)
|
| 46 |
+
min_M = []
|
| 47 |
+
min_index = []
|
| 48 |
+
min_error = float('inf')
|
| 49 |
+
if mode == 'arcface':
|
| 50 |
+
if image_size == 112:
|
| 51 |
+
src = arcface_src
|
| 52 |
+
else:
|
| 53 |
+
src = float(image_size) / 112 * arcface_src
|
| 54 |
+
else:
|
| 55 |
+
src = src_map[image_size]
|
| 56 |
+
for i in np.arange(src.shape[0]):
|
| 57 |
+
tform.estimate(lmk, src[i])
|
| 58 |
+
M = tform.params[0:2, :]
|
| 59 |
+
results = np.dot(M, lmk_tran.T)
|
| 60 |
+
results = results.T
|
| 61 |
+
error = np.sum(np.sqrt(np.sum((results - src[i])**2, axis=1)))
|
| 62 |
+
# print(error)
|
| 63 |
+
if error < min_error:
|
| 64 |
+
min_error = error
|
| 65 |
+
min_M = M
|
| 66 |
+
min_index = i
|
| 67 |
+
return min_M, min_index
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def norm_crop(img, landmark, image_size=112, mode='arcface'):
|
| 71 |
+
M, pose_index = estimate_norm(landmark, image_size, mode)
|
| 72 |
+
warped = cv2.warpAffine(img, M, (image_size, image_size), borderValue=0.0)
|
| 73 |
+
return warped
|
| 74 |
+
|
| 75 |
+
def square_crop(im, S):
|
| 76 |
+
if im.shape[0] > im.shape[1]:
|
| 77 |
+
height = S
|
| 78 |
+
width = int(float(im.shape[1]) / im.shape[0] * S)
|
| 79 |
+
scale = float(S) / im.shape[0]
|
| 80 |
+
else:
|
| 81 |
+
width = S
|
| 82 |
+
height = int(float(im.shape[0]) / im.shape[1] * S)
|
| 83 |
+
scale = float(S) / im.shape[1]
|
| 84 |
+
resized_im = cv2.resize(im, (width, height))
|
| 85 |
+
det_im = np.zeros((S, S, 3), dtype=np.uint8)
|
| 86 |
+
det_im[:resized_im.shape[0], :resized_im.shape[1], :] = resized_im
|
| 87 |
+
return det_im, scale
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def transform(data, center, output_size, scale, rotation):
|
| 91 |
+
scale_ratio = scale
|
| 92 |
+
rot = float(rotation) * np.pi / 180.0
|
| 93 |
+
#translation = (output_size/2-center[0]*scale_ratio, output_size/2-center[1]*scale_ratio)
|
| 94 |
+
t1 = trans.SimilarityTransform(scale=scale_ratio)
|
| 95 |
+
cx = center[0] * scale_ratio
|
| 96 |
+
cy = center[1] * scale_ratio
|
| 97 |
+
t2 = trans.SimilarityTransform(translation=(-1 * cx, -1 * cy))
|
| 98 |
+
t3 = trans.SimilarityTransform(rotation=rot)
|
| 99 |
+
t4 = trans.SimilarityTransform(translation=(output_size / 2,
|
| 100 |
+
output_size / 2))
|
| 101 |
+
t = t1 + t2 + t3 + t4
|
| 102 |
+
M = t.params[0:2]
|
| 103 |
+
cropped = cv2.warpAffine(data,
|
| 104 |
+
M, (output_size, output_size),
|
| 105 |
+
borderValue=0.0)
|
| 106 |
+
return cropped, M
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def trans_points2d(pts, M):
|
| 110 |
+
new_pts = np.zeros(shape=pts.shape, dtype=np.float32)
|
| 111 |
+
for i in range(pts.shape[0]):
|
| 112 |
+
pt = pts[i]
|
| 113 |
+
new_pt = np.array([pt[0], pt[1], 1.], dtype=np.float32)
|
| 114 |
+
new_pt = np.dot(M, new_pt)
|
| 115 |
+
#print('new_pt', new_pt.shape, new_pt)
|
| 116 |
+
new_pts[i] = new_pt[0:2]
|
| 117 |
+
|
| 118 |
+
return new_pts
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def trans_points3d(pts, M):
|
| 122 |
+
scale = np.sqrt(M[0][0] * M[0][0] + M[0][1] * M[0][1])
|
| 123 |
+
#print(scale)
|
| 124 |
+
new_pts = np.zeros(shape=pts.shape, dtype=np.float32)
|
| 125 |
+
for i in range(pts.shape[0]):
|
| 126 |
+
pt = pts[i]
|
| 127 |
+
new_pt = np.array([pt[0], pt[1], 1.], dtype=np.float32)
|
| 128 |
+
new_pt = np.dot(M, new_pt)
|
| 129 |
+
#print('new_pt', new_pt.shape, new_pt)
|
| 130 |
+
new_pts[i][0:2] = new_pt[0:2]
|
| 131 |
+
new_pts[i][2] = pts[i][2] * scale
|
| 132 |
+
|
| 133 |
+
return new_pts
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def trans_points(pts, M):
|
| 137 |
+
if pts.shape[1] == 2:
|
| 138 |
+
return trans_points2d(pts, M)
|
| 139 |
+
else:
|
| 140 |
+
return trans_points3d(pts, M)
|
| 141 |
+
|
recognition/main.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import os.path as osp
|
| 5 |
+
import argparse
|
| 6 |
+
import cv2
|
| 7 |
+
import numpy as np
|
| 8 |
+
import onnxruntime
|
| 9 |
+
from scrfd import SCRFD
|
| 10 |
+
from arcface_onnx import ArcFaceONNX
|
| 11 |
+
|
| 12 |
+
onnxruntime.set_default_logger_severity(5)
|
| 13 |
+
|
| 14 |
+
assets_dir = osp.expanduser('~/.insightface/models/buffalo_l')
|
| 15 |
+
|
| 16 |
+
detector = SCRFD(os.path.join(assets_dir, 'det_10g.onnx'))
|
| 17 |
+
detector.prepare(0)
|
| 18 |
+
model_path = os.path.join(assets_dir, 'w600k_r50.onnx')
|
| 19 |
+
rec = ArcFaceONNX(model_path)
|
| 20 |
+
rec.prepare(0)
|
| 21 |
+
|
| 22 |
+
def parse_args() -> argparse.Namespace:
|
| 23 |
+
parser = argparse.ArgumentParser()
|
| 24 |
+
parser.add_argument('img1', type=str)
|
| 25 |
+
parser.add_argument('img2', type=str)
|
| 26 |
+
return parser.parse_args()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def func(args):
|
| 30 |
+
image1 = cv2.imread(args.img1)
|
| 31 |
+
image2 = cv2.imread(args.img2)
|
| 32 |
+
bboxes1, kpss1 = detector.autodetect(image1, max_num=1)
|
| 33 |
+
if bboxes1.shape[0]==0:
|
| 34 |
+
return -1.0, "Face not found in Image-1"
|
| 35 |
+
bboxes2, kpss2 = detector.autodetect(image2, max_num=1)
|
| 36 |
+
if bboxes2.shape[0]==0:
|
| 37 |
+
return -1.0, "Face not found in Image-2"
|
| 38 |
+
kps1 = kpss1[0]
|
| 39 |
+
kps2 = kpss2[0]
|
| 40 |
+
feat1 = rec.get(image1, kps1)
|
| 41 |
+
feat2 = rec.get(image2, kps2)
|
| 42 |
+
sim = rec.compute_sim(feat1, feat2)
|
| 43 |
+
if sim<0.2:
|
| 44 |
+
conclu = 'They are NOT the same person'
|
| 45 |
+
elif sim>=0.2 and sim<0.28:
|
| 46 |
+
conclu = 'They are LIKELY TO be the same person'
|
| 47 |
+
else:
|
| 48 |
+
conclu = 'They ARE the same person'
|
| 49 |
+
return sim, conclu
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
if __name__ == '__main__':
|
| 54 |
+
args = parse_args()
|
| 55 |
+
output = func(args)
|
| 56 |
+
print('sim: %.4f, message: %s'%(output[0], output[1]))
|
| 57 |
+
|
recognition/scrfd.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from __future__ import division
|
| 3 |
+
import datetime
|
| 4 |
+
import numpy as np
|
| 5 |
+
#import onnx
|
| 6 |
+
import onnxruntime
|
| 7 |
+
import os
|
| 8 |
+
import os.path as osp
|
| 9 |
+
import cv2
|
| 10 |
+
import sys
|
| 11 |
+
|
| 12 |
+
def softmax(z):
|
| 13 |
+
assert len(z.shape) == 2
|
| 14 |
+
s = np.max(z, axis=1)
|
| 15 |
+
s = s[:, np.newaxis] # necessary step to do broadcasting
|
| 16 |
+
e_x = np.exp(z - s)
|
| 17 |
+
div = np.sum(e_x, axis=1)
|
| 18 |
+
div = div[:, np.newaxis] # dito
|
| 19 |
+
return e_x / div
|
| 20 |
+
|
| 21 |
+
def distance2bbox(points, distance, max_shape=None):
|
| 22 |
+
"""Decode distance prediction to bounding box.
|
| 23 |
+
|
| 24 |
+
Args:
|
| 25 |
+
points (Tensor): Shape (n, 2), [x, y].
|
| 26 |
+
distance (Tensor): Distance from the given point to 4
|
| 27 |
+
boundaries (left, top, right, bottom).
|
| 28 |
+
max_shape (tuple): Shape of the image.
|
| 29 |
+
|
| 30 |
+
Returns:
|
| 31 |
+
Tensor: Decoded bboxes.
|
| 32 |
+
"""
|
| 33 |
+
x1 = points[:, 0] - distance[:, 0]
|
| 34 |
+
y1 = points[:, 1] - distance[:, 1]
|
| 35 |
+
x2 = points[:, 0] + distance[:, 2]
|
| 36 |
+
y2 = points[:, 1] + distance[:, 3]
|
| 37 |
+
if max_shape is not None:
|
| 38 |
+
x1 = x1.clamp(min=0, max=max_shape[1])
|
| 39 |
+
y1 = y1.clamp(min=0, max=max_shape[0])
|
| 40 |
+
x2 = x2.clamp(min=0, max=max_shape[1])
|
| 41 |
+
y2 = y2.clamp(min=0, max=max_shape[0])
|
| 42 |
+
return np.stack([x1, y1, x2, y2], axis=-1)
|
| 43 |
+
|
| 44 |
+
def distance2kps(points, distance, max_shape=None):
|
| 45 |
+
"""Decode distance prediction to bounding box.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
points (Tensor): Shape (n, 2), [x, y].
|
| 49 |
+
distance (Tensor): Distance from the given point to 4
|
| 50 |
+
boundaries (left, top, right, bottom).
|
| 51 |
+
max_shape (tuple): Shape of the image.
|
| 52 |
+
|
| 53 |
+
Returns:
|
| 54 |
+
Tensor: Decoded bboxes.
|
| 55 |
+
"""
|
| 56 |
+
preds = []
|
| 57 |
+
for i in range(0, distance.shape[1], 2):
|
| 58 |
+
px = points[:, i%2] + distance[:, i]
|
| 59 |
+
py = points[:, i%2+1] + distance[:, i+1]
|
| 60 |
+
if max_shape is not None:
|
| 61 |
+
px = px.clamp(min=0, max=max_shape[1])
|
| 62 |
+
py = py.clamp(min=0, max=max_shape[0])
|
| 63 |
+
preds.append(px)
|
| 64 |
+
preds.append(py)
|
| 65 |
+
return np.stack(preds, axis=-1)
|
| 66 |
+
|
| 67 |
+
class SCRFD:
|
| 68 |
+
def __init__(self, model_file=None, session=None):
|
| 69 |
+
import onnxruntime
|
| 70 |
+
self.model_file = model_file
|
| 71 |
+
self.session = session
|
| 72 |
+
self.taskname = 'detection'
|
| 73 |
+
self.batched = False
|
| 74 |
+
if self.session is None:
|
| 75 |
+
assert self.model_file is not None
|
| 76 |
+
assert osp.exists(self.model_file)
|
| 77 |
+
self.session = onnxruntime.InferenceSession(self.model_file, providers=['CoreMLExecutionProvider','CUDAExecutionProvider'])
|
| 78 |
+
self.center_cache = {}
|
| 79 |
+
self.nms_thresh = 0.4
|
| 80 |
+
self.det_thresh = 0.5
|
| 81 |
+
self._init_vars()
|
| 82 |
+
|
| 83 |
+
def _init_vars(self):
|
| 84 |
+
input_cfg = self.session.get_inputs()[0]
|
| 85 |
+
input_shape = input_cfg.shape
|
| 86 |
+
#print(input_shape)
|
| 87 |
+
if isinstance(input_shape[2], str):
|
| 88 |
+
self.input_size = None
|
| 89 |
+
else:
|
| 90 |
+
self.input_size = tuple(input_shape[2:4][::-1])
|
| 91 |
+
#print('image_size:', self.image_size)
|
| 92 |
+
input_name = input_cfg.name
|
| 93 |
+
self.input_shape = input_shape
|
| 94 |
+
outputs = self.session.get_outputs()
|
| 95 |
+
if len(outputs[0].shape) == 3:
|
| 96 |
+
self.batched = True
|
| 97 |
+
output_names = []
|
| 98 |
+
for o in outputs:
|
| 99 |
+
output_names.append(o.name)
|
| 100 |
+
self.input_name = input_name
|
| 101 |
+
self.output_names = output_names
|
| 102 |
+
self.input_mean = 127.5
|
| 103 |
+
self.input_std = 128.0
|
| 104 |
+
#print(self.output_names)
|
| 105 |
+
#assert len(outputs)==10 or len(outputs)==15
|
| 106 |
+
self.use_kps = False
|
| 107 |
+
self._anchor_ratio = 1.0
|
| 108 |
+
self._num_anchors = 1
|
| 109 |
+
if len(outputs)==6:
|
| 110 |
+
self.fmc = 3
|
| 111 |
+
self._feat_stride_fpn = [8, 16, 32]
|
| 112 |
+
self._num_anchors = 2
|
| 113 |
+
elif len(outputs)==9:
|
| 114 |
+
self.fmc = 3
|
| 115 |
+
self._feat_stride_fpn = [8, 16, 32]
|
| 116 |
+
self._num_anchors = 2
|
| 117 |
+
self.use_kps = True
|
| 118 |
+
elif len(outputs)==10:
|
| 119 |
+
self.fmc = 5
|
| 120 |
+
self._feat_stride_fpn = [8, 16, 32, 64, 128]
|
| 121 |
+
self._num_anchors = 1
|
| 122 |
+
elif len(outputs)==15:
|
| 123 |
+
self.fmc = 5
|
| 124 |
+
self._feat_stride_fpn = [8, 16, 32, 64, 128]
|
| 125 |
+
self._num_anchors = 1
|
| 126 |
+
self.use_kps = True
|
| 127 |
+
|
| 128 |
+
def prepare(self, ctx_id, **kwargs):
|
| 129 |
+
if ctx_id<0:
|
| 130 |
+
self.session.set_providers(['CPUExecutionProvider'])
|
| 131 |
+
nms_thresh = kwargs.get('nms_thresh', None)
|
| 132 |
+
if nms_thresh is not None:
|
| 133 |
+
self.nms_thresh = nms_thresh
|
| 134 |
+
det_thresh = kwargs.get('det_thresh', None)
|
| 135 |
+
if det_thresh is not None:
|
| 136 |
+
self.det_thresh = det_thresh
|
| 137 |
+
input_size = kwargs.get('input_size', None)
|
| 138 |
+
if input_size is not None:
|
| 139 |
+
if self.input_size is not None:
|
| 140 |
+
print('warning: det_size is already set in scrfd model, ignore')
|
| 141 |
+
else:
|
| 142 |
+
self.input_size = input_size
|
| 143 |
+
|
| 144 |
+
def forward(self, img, threshold):
|
| 145 |
+
scores_list = []
|
| 146 |
+
bboxes_list = []
|
| 147 |
+
kpss_list = []
|
| 148 |
+
input_size = tuple(img.shape[0:2][::-1])
|
| 149 |
+
blob = cv2.dnn.blobFromImage(img, 1.0/self.input_std, input_size, (self.input_mean, self.input_mean, self.input_mean), swapRB=True)
|
| 150 |
+
net_outs = self.session.run(self.output_names, {self.input_name : blob})
|
| 151 |
+
|
| 152 |
+
input_height = blob.shape[2]
|
| 153 |
+
input_width = blob.shape[3]
|
| 154 |
+
fmc = self.fmc
|
| 155 |
+
for idx, stride in enumerate(self._feat_stride_fpn):
|
| 156 |
+
# If model support batch dim, take first output
|
| 157 |
+
if self.batched:
|
| 158 |
+
scores = net_outs[idx][0]
|
| 159 |
+
bbox_preds = net_outs[idx + fmc][0]
|
| 160 |
+
bbox_preds = bbox_preds * stride
|
| 161 |
+
if self.use_kps:
|
| 162 |
+
kps_preds = net_outs[idx + fmc * 2][0] * stride
|
| 163 |
+
# If model doesn't support batching take output as is
|
| 164 |
+
else:
|
| 165 |
+
scores = net_outs[idx]
|
| 166 |
+
bbox_preds = net_outs[idx + fmc]
|
| 167 |
+
bbox_preds = bbox_preds * stride
|
| 168 |
+
if self.use_kps:
|
| 169 |
+
kps_preds = net_outs[idx + fmc * 2] * stride
|
| 170 |
+
|
| 171 |
+
height = input_height // stride
|
| 172 |
+
width = input_width // stride
|
| 173 |
+
K = height * width
|
| 174 |
+
key = (height, width, stride)
|
| 175 |
+
if key in self.center_cache:
|
| 176 |
+
anchor_centers = self.center_cache[key]
|
| 177 |
+
else:
|
| 178 |
+
#solution-1, c style:
|
| 179 |
+
#anchor_centers = np.zeros( (height, width, 2), dtype=np.float32 )
|
| 180 |
+
#for i in range(height):
|
| 181 |
+
# anchor_centers[i, :, 1] = i
|
| 182 |
+
#for i in range(width):
|
| 183 |
+
# anchor_centers[:, i, 0] = i
|
| 184 |
+
|
| 185 |
+
#solution-2:
|
| 186 |
+
#ax = np.arange(width, dtype=np.float32)
|
| 187 |
+
#ay = np.arange(height, dtype=np.float32)
|
| 188 |
+
#xv, yv = np.meshgrid(np.arange(width), np.arange(height))
|
| 189 |
+
#anchor_centers = np.stack([xv, yv], axis=-1).astype(np.float32)
|
| 190 |
+
|
| 191 |
+
#solution-3:
|
| 192 |
+
anchor_centers = np.stack(np.mgrid[:height, :width][::-1], axis=-1).astype(np.float32)
|
| 193 |
+
#print(anchor_centers.shape)
|
| 194 |
+
|
| 195 |
+
anchor_centers = (anchor_centers * stride).reshape( (-1, 2) )
|
| 196 |
+
if self._num_anchors>1:
|
| 197 |
+
anchor_centers = np.stack([anchor_centers]*self._num_anchors, axis=1).reshape( (-1,2) )
|
| 198 |
+
if len(self.center_cache)<100:
|
| 199 |
+
self.center_cache[key] = anchor_centers
|
| 200 |
+
|
| 201 |
+
pos_inds = np.where(scores>=threshold)[0]
|
| 202 |
+
bboxes = distance2bbox(anchor_centers, bbox_preds)
|
| 203 |
+
pos_scores = scores[pos_inds]
|
| 204 |
+
pos_bboxes = bboxes[pos_inds]
|
| 205 |
+
scores_list.append(pos_scores)
|
| 206 |
+
bboxes_list.append(pos_bboxes)
|
| 207 |
+
if self.use_kps:
|
| 208 |
+
kpss = distance2kps(anchor_centers, kps_preds)
|
| 209 |
+
#kpss = kps_preds
|
| 210 |
+
kpss = kpss.reshape( (kpss.shape[0], -1, 2) )
|
| 211 |
+
pos_kpss = kpss[pos_inds]
|
| 212 |
+
kpss_list.append(pos_kpss)
|
| 213 |
+
return scores_list, bboxes_list, kpss_list
|
| 214 |
+
|
| 215 |
+
def detect(self, img, input_size = None, thresh=None, max_num=0, metric='default'):
|
| 216 |
+
assert input_size is not None or self.input_size is not None
|
| 217 |
+
input_size = self.input_size if input_size is None else input_size
|
| 218 |
+
|
| 219 |
+
im_ratio = float(img.shape[0]) / img.shape[1]
|
| 220 |
+
model_ratio = float(input_size[1]) / input_size[0]
|
| 221 |
+
if im_ratio>model_ratio:
|
| 222 |
+
new_height = input_size[1]
|
| 223 |
+
new_width = int(new_height / im_ratio)
|
| 224 |
+
else:
|
| 225 |
+
new_width = input_size[0]
|
| 226 |
+
new_height = int(new_width * im_ratio)
|
| 227 |
+
det_scale = float(new_height) / img.shape[0]
|
| 228 |
+
resized_img = cv2.resize(img, (new_width, new_height))
|
| 229 |
+
det_img = np.zeros( (input_size[1], input_size[0], 3), dtype=np.uint8 )
|
| 230 |
+
det_img[:new_height, :new_width, :] = resized_img
|
| 231 |
+
det_thresh = thresh if thresh is not None else self.det_thresh
|
| 232 |
+
|
| 233 |
+
scores_list, bboxes_list, kpss_list = self.forward(det_img, det_thresh)
|
| 234 |
+
|
| 235 |
+
scores = np.vstack(scores_list)
|
| 236 |
+
scores_ravel = scores.ravel()
|
| 237 |
+
order = scores_ravel.argsort()[::-1]
|
| 238 |
+
bboxes = np.vstack(bboxes_list) / det_scale
|
| 239 |
+
if self.use_kps:
|
| 240 |
+
kpss = np.vstack(kpss_list) / det_scale
|
| 241 |
+
pre_det = np.hstack((bboxes, scores)).astype(np.float32, copy=False)
|
| 242 |
+
pre_det = pre_det[order, :]
|
| 243 |
+
keep = self.nms(pre_det)
|
| 244 |
+
det = pre_det[keep, :]
|
| 245 |
+
if self.use_kps:
|
| 246 |
+
kpss = kpss[order,:,:]
|
| 247 |
+
kpss = kpss[keep,:,:]
|
| 248 |
+
else:
|
| 249 |
+
kpss = None
|
| 250 |
+
if max_num > 0 and det.shape[0] > max_num:
|
| 251 |
+
area = (det[:, 2] - det[:, 0]) * (det[:, 3] -
|
| 252 |
+
det[:, 1])
|
| 253 |
+
img_center = img.shape[0] // 2, img.shape[1] // 2
|
| 254 |
+
offsets = np.vstack([
|
| 255 |
+
(det[:, 0] + det[:, 2]) / 2 - img_center[1],
|
| 256 |
+
(det[:, 1] + det[:, 3]) / 2 - img_center[0]
|
| 257 |
+
])
|
| 258 |
+
offset_dist_squared = np.sum(np.power(offsets, 2.0), 0)
|
| 259 |
+
if metric=='max':
|
| 260 |
+
values = area
|
| 261 |
+
else:
|
| 262 |
+
values = area - offset_dist_squared * 2.0 # some extra weight on the centering
|
| 263 |
+
bindex = np.argsort(
|
| 264 |
+
values)[::-1] # some extra weight on the centering
|
| 265 |
+
bindex = bindex[0:max_num]
|
| 266 |
+
det = det[bindex, :]
|
| 267 |
+
if kpss is not None:
|
| 268 |
+
kpss = kpss[bindex, :]
|
| 269 |
+
return det, kpss
|
| 270 |
+
|
| 271 |
+
def autodetect(self, img, max_num=0, metric='max'):
|
| 272 |
+
bboxes, kpss = self.detect(img, input_size=(640, 640), thresh=0.5)
|
| 273 |
+
bboxes2, kpss2 = self.detect(img, input_size=(128, 128), thresh=0.5)
|
| 274 |
+
bboxes_all = np.concatenate([bboxes, bboxes2], axis=0)
|
| 275 |
+
kpss_all = np.concatenate([kpss, kpss2], axis=0)
|
| 276 |
+
keep = self.nms(bboxes_all)
|
| 277 |
+
det = bboxes_all[keep,:]
|
| 278 |
+
kpss = kpss_all[keep,:]
|
| 279 |
+
if max_num > 0 and det.shape[0] > max_num:
|
| 280 |
+
area = (det[:, 2] - det[:, 0]) * (det[:, 3] -
|
| 281 |
+
det[:, 1])
|
| 282 |
+
img_center = img.shape[0] // 2, img.shape[1] // 2
|
| 283 |
+
offsets = np.vstack([
|
| 284 |
+
(det[:, 0] + det[:, 2]) / 2 - img_center[1],
|
| 285 |
+
(det[:, 1] + det[:, 3]) / 2 - img_center[0]
|
| 286 |
+
])
|
| 287 |
+
offset_dist_squared = np.sum(np.power(offsets, 2.0), 0)
|
| 288 |
+
if metric=='max':
|
| 289 |
+
values = area
|
| 290 |
+
else:
|
| 291 |
+
values = area - offset_dist_squared * 2.0 # some extra weight on the centering
|
| 292 |
+
bindex = np.argsort(
|
| 293 |
+
values)[::-1] # some extra weight on the centering
|
| 294 |
+
bindex = bindex[0:max_num]
|
| 295 |
+
det = det[bindex, :]
|
| 296 |
+
if kpss is not None:
|
| 297 |
+
kpss = kpss[bindex, :]
|
| 298 |
+
return det, kpss
|
| 299 |
+
|
| 300 |
+
def nms(self, dets):
|
| 301 |
+
thresh = self.nms_thresh
|
| 302 |
+
x1 = dets[:, 0]
|
| 303 |
+
y1 = dets[:, 1]
|
| 304 |
+
x2 = dets[:, 2]
|
| 305 |
+
y2 = dets[:, 3]
|
| 306 |
+
scores = dets[:, 4]
|
| 307 |
+
|
| 308 |
+
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
|
| 309 |
+
order = scores.argsort()[::-1]
|
| 310 |
+
|
| 311 |
+
keep = []
|
| 312 |
+
while order.size > 0:
|
| 313 |
+
i = order[0]
|
| 314 |
+
keep.append(i)
|
| 315 |
+
xx1 = np.maximum(x1[i], x1[order[1:]])
|
| 316 |
+
yy1 = np.maximum(y1[i], y1[order[1:]])
|
| 317 |
+
xx2 = np.minimum(x2[i], x2[order[1:]])
|
| 318 |
+
yy2 = np.minimum(y2[i], y2[order[1:]])
|
| 319 |
+
|
| 320 |
+
w = np.maximum(0.0, xx2 - xx1 + 1)
|
| 321 |
+
h = np.maximum(0.0, yy2 - yy1 + 1)
|
| 322 |
+
inter = w * h
|
| 323 |
+
ovr = inter / (areas[i] + areas[order[1:]] - inter)
|
| 324 |
+
|
| 325 |
+
inds = np.where(ovr <= thresh)[0]
|
| 326 |
+
order = order[inds + 1]
|
| 327 |
+
|
| 328 |
+
return keep
|
| 329 |
+
|