repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
insightface | recognition/partial_fc/mxnet/symbol/memonger.py | .py | import mxnet as mx
import math
def prod(shape):
"""Get product of the shape.
"""
ret = 1
for s in shape:
ret *= s
return ret
def is_param(name):
"""Quick script to check if name is a parameter.
"""
if name == 'data':
return False
if name.endswith('weight'):
... | 176 | 5,288 |
insightface | recognition/partial_fc/mxnet/symbol/symbol_utils.py | .py | import sys
import os
import mxnet as mx
sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
from default import config
def Conv(**kwargs):
# name = kwargs.get('name')
# _weight = mx.symbol.Variable(name+'_weight')
# _bias = mx.symbol.Variable(name+'_bias', lr_mult=2.0, wd_mult=0.0)
# bo... | 597 | 24,234 |
insightface | recognition/vpl/vpl.py | .py | import logging
import os
import torch
import torch.distributed as dist
from torch.nn import Module
from torch.nn.functional import normalize, linear
from torch.nn.parameter import Parameter
class VPL(Module):
"""
Modified from Partial-FC
"""
@torch.no_grad()
def __init__(self, rank, local_rank, ... | 187 | 8,104 |
insightface | recognition/vpl/onnx_ijbc.py | .py | import argparse
import os
import pickle
import timeit
import cv2
import mxnet as mx
import numpy as np
import pandas as pd
import prettytable
import skimage.transform
from sklearn.metrics import roc_curve
from sklearn.preprocessing import normalize
from onnx_helper import ArcFaceORT
SRC = np.array(
[
[30... | 268 | 10,321 |
insightface | recognition/vpl/inference.py | .py | import argparse
import cv2
import numpy as np
import torch
from backbones import get_model
@torch.no_grad()
def inference(weight, name, img):
if img is None:
img = np.random.randint(0, 255, size=(112, 112, 3), dtype=np.uint8)
else:
img = cv2.imread(img)
img = cv2.cvtColor(img, cv2.COLOR... | 35 | 991 |
insightface | recognition/vpl/losses.py | .py | import torch
from torch import nn
def get_loss(name):
if name == "cosface":
return CosFace()
elif name == "arcface":
return ArcFace()
else:
raise ValueError()
class CosFace(nn.Module):
def __init__(self, s=64.0, m=0.40):
super(CosFace, self).__init__()
self.s = ... | 41 | 1,135 |
insightface | recognition/vpl/train.py | .py | import argparse
import logging
import os
import time
import torch
import torch.distributed as dist
import torch.nn.functional as F
import torch.utils.data.distributed
from torch.nn.utils import clip_grad_norm_
import losses
from backbones import get_model
from dataset import MXFaceDataset, DataLoaderX
from torch.util... | 181 | 7,411 |
insightface | recognition/vpl/torch2onnx.py | .py | import numpy as np
import onnx
import torch
def convert_onnx(net, path_module, output, opset=11, simplify=False):
assert isinstance(net, torch.nn.Module)
img = np.random.randint(0, 255, size=(112, 112, 3), dtype=np.int32)
img = img.astype(np.float)
img = (img / 255. - 0.5) / 0.5 # torch style norm
... | 60 | 2,364 |
insightface | recognition/vpl/onnx_helper.py | .py | import argparse
import datetime
import os
import os.path as osp
import cv2
import numpy as np
import onnx
import onnxruntime
from onnx import numpy_helper
class ArcFaceORT:
def __init__(self, model_path):
self.model_path = model_path
def check(self, test_img=None):
max_model_size_mb = 1024
... | 200 | 8,088 |
insightface | recognition/vpl/eval_ijbc.py | .py | # coding: utf-8
import os
import pickle
import matplotlib
import pandas as pd
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import timeit
import sklearn
import argparse
from sklearn.metrics import roc_curve, auc
from menpo.visualize.viewmatplotlib import sample_colours_from_colourmap
from prettytable import... | 484 | 17,271 |
insightface | recognition/vpl/dataset.py | .py | import numbers
import os
import queue as Queue
import threading
import mxnet as mx
import numpy as np
import torch
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
class BackgroundGenerator(threading.Thread):
def __init__(self, generator, local_rank, max_prefetch=6):
su... | 114 | 3,591 |
insightface | recognition/vpl/backbones/iresnet1024.py | .py | import torch
from torch import nn
assert torch.__version__ >= "1.8.1"
from torch.utils.checkpoint import checkpoint_sequential
__all__ = ['iresnet1024']
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes,
out... | 172 | 6,619 |
insightface | recognition/vpl/backbones/__init__.py | .py | from .iresnet import iresnet18, iresnet34, iresnet50, iresnet100, iresnet200
def get_model(name, **kwargs):
if name == "r18":
return iresnet18(False, **kwargs)
elif name == "r34":
return iresnet34(False, **kwargs)
elif name == "r50":
return iresnet50(False, **kwargs)
elif name ... | 20 | 594 |
insightface | recognition/vpl/backbones/iresnet.py | .py | import torch
from torch import nn
__all__ = ['iresnet18', 'iresnet34', 'iresnet50', 'iresnet100', 'iresnet200']
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes,
out_planes,
kernel_size=... | 188 | 7,149 |
insightface | recognition/vpl/utils/utils_amp.py | .py | from typing import Dict, List
import torch
from torch._six import container_abcs
from torch.cuda.amp import GradScaler
class _MultiDeviceReplicator(object):
"""
Lazily serves copies of a tensor to requested devices. Copies are cached per-device.
"""
def __init__(self, master_tensor: torch.Tensor) -... | 82 | 3,187 |
insightface | recognition/vpl/utils/utils_callbacks.py | .py | import logging
import os
import time
from typing import List
import torch
from eval import verification
from torch2onnx import convert_onnx
from utils.utils_logging import AverageMeter
class CallBackVerification(object):
def __init__(self, frequent, rank, val_targets, rec_prefix, image_size=(112, 112)):
... | 113 | 4,929 |
insightface | recognition/vpl/utils/utils_config.py | .py | import importlib
import os
import os.path as osp
def get_config(config_file):
assert config_file.startswith('configs/'), 'config file setting must start with configs/'
temp_config_name = osp.basename(config_file)
temp_module_name = osp.splitext(temp_config_name)[0]
config = importlib.import_module("con... | 17 | 579 |
insightface | recognition/vpl/utils/utils_dist.py | .py | import torch
@torch.no_grad()
def concat_all_gather(tensor):
"""
Performs all_gather operation on the provided tensors.
*** Warning ***: torch.distributed.all_gather has no gradient.
"""
tensors_gather = [torch.ones_like(tensor)
for _ in range(torch.distributed.get_world_size())]
torch.distributed.all_gather(t... | 58 | 1,471 |
insightface | recognition/vpl/configs/example_ms1mv3.py | .py | from easydict import EasyDict as edict
config = edict()
config.dataset = "ms1mv3"
config.fp16 = True
config.batch_size = 128
config.vpl = {'start_iters': 8000, 'allowed_delta': 200, 'lambda': 0.15, 'mode': 0, 'momentum': False}
config.rec = "/train_tmp/ms1m-retinaface-t1"
config.num_classes = 93431
config.num_image =... | 19 | 532 |
insightface | recognition/vpl/configs/base.py | .py | from easydict import EasyDict as edict
config = edict()
config.embedding_size = 512
config.sample_rate = 1
config.fp16 = False
config.tf32 = False
config.momentum = 0.9
config.weight_decay = 5e-4
config.batch_size = 128
config.lr = 0.1 # when batch size is 512
config.warmup_epoch = -1
config.loss = 'arcface'
config.n... | 20 | 536 |
insightface | recognition/arcface_mxnet/metric.py | .py | import numpy as np
import mxnet as mx
class AccMetric(mx.metric.EvalMetric):
def __init__(self):
self.axis = 1
super(AccMetric, self).__init__('acc',
axis=self.axis,
output_names=None,
... | 51 | 1,731 |
insightface | recognition/arcface_mxnet/train.py | .py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import math
import random
import logging
import sklearn
import pickle
import numpy as np
import mxnet as mx
from mxnet import ndarray as nd
import argparse
import mxnet.optimizer as optimiz... | 485 | 19,130 |
insightface | recognition/arcface_mxnet/triplet_image_iter.py | .py | # THIS FILE IS FOR EXPERIMENTS, USE image_iter.py FOR NORMAL IMAGE LOADING.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import random
import logging
import sys
import numbers
import math
import sklearn
import datetime
import numpy as np
import ... | 629 | 24,969 |
insightface | recognition/arcface_mxnet/train_parall.py | .py | '''
@author: insightface
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import math
import random
import logging
import pickle
import sklearn
import numpy as np
#from image_iter import FaceImageIter
from image_iter import get_face_... | 452 | 16,556 |
insightface | recognition/arcface_mxnet/image_iter.py | .py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import random
import logging
import sys
import numbers
import math
import sklearn
import datetime
import numpy as np
import cv2
import mxnet as mx
from mxnet import ndarray as nd
from mxnet import io... | 368 | 13,473 |
insightface | recognition/arcface_mxnet/parall_module_local_v1.py | .py | '''
@author: insightface
'''
import logging
import copy
import time
import os
import mxnet as mx
import numpy as np
from mxnet import context as ctx
from mxnet.initializer import Uniform
from mxnet.module.base_module import BaseModule
from mxnet.module.module import Module
from mxnet import metric
from mxnet.model im... | 613 | 25,502 |
insightface | recognition/arcface_mxnet/verification.py | .py | """Helper for evaluation on the Labeled Faces in the Wild dataset
"""
# MIT License
#
# Copyright (c) 2016 David Sandberg
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restricti... | 681 | 26,306 |
insightface | recognition/arcface_mxnet/sample_config.py | .py | import numpy as np
import os
from easydict import EasyDict as edict
config = edict()
config.bn_mom = 0.9
config.workspace = 256
config.emb_size = 512
config.ckpt_embedding = True
config.net_se = 0
config.net_act = 'prelu'
config.net_unit = 3
config.net_input = 1
config.net_blocks = [1, 4, 6, 2]
config.net_output = 'E... | 225 | 5,724 |
insightface | recognition/arcface_mxnet/symbol/vargfacenet.py | .py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | 579 | 24,498 |
insightface | recognition/arcface_mxnet/symbol/fmobilefacenet.py | .py | import sys
import os
import mxnet as mx
import symbol_utils
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from config import config
def Act(data, act_type, name):
#ignore param act_type, set it in this function
if act_type == 'prelu':
body = mx.sym.LeakyReLU(data=data, act_type='prelu... | 225 | 7,365 |
insightface | recognition/arcface_mxnet/symbol/fmobilenet.py | .py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | 276 | 9,660 |
insightface | recognition/arcface_mxnet/symbol/symbol_utils.py | .py | import sys
import os
import mxnet as mx
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from config import config
def Conv(**kwargs):
#name = kwargs.get('name')
#_weight = mx.symbol.Variable(name+'_weight')
#_bias = mx.symbol.Variable(name+'_bias', lr_mult=2.0, wd_mult=0.0)
#body = mx.s... | 596 | 24,212 |
insightface | recognition/arcface_mxnet/symbol/memonger_v2.py | .py | import mxnet as mx
import math
def prod(shape):
"""Get product of the shape.
"""
ret = 1
for s in shape:
ret *= s
return ret
def is_param(name):
"""Quick script to check if name is a parameter.
"""
if name == 'data':
return False
if name.endswith('weight'):
... | 301 | 9,748 |
insightface | recognition/arcface_mxnet/symbol/fdensenet.py | .py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | 170 | 5,772 |
insightface | recognition/arcface_mxnet/symbol/fmnasnet.py | .py | import sys
import os
import mxnet as mx
import mxnet.ndarray as nd
import mxnet.gluon as gluon
import mxnet.gluon.nn as nn
import mxnet.autograd as ag
import symbol_utils
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from config import config
def Act():
if config.net_act == 'prelu':
retur... | 214 | 7,212 |
insightface | recognition/arcface_mxnet/symbol/fresnet.py | .py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | 1,192 | 47,119 |
insightface | recognition/arcface_mxnet/common/rec2shufrec.py | .py | import os
import os.path as osp
import sys
import datetime
import glob
import shutil
import numbers
import mxnet as mx
from mxnet import ndarray as nd
from mxnet import io
from mxnet import recordio
import random
import argparse
import cv2
import time
import numpy as np
def main(args):
ds = args.input
path_img... | 73 | 2,532 |
insightface | recognition/arcface_mxnet/common/flops_counter.py | .py | '''
@author: insightface
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import os
import json
import argparse
import numpy as np
import mxnet as mx
def is_no_bias(attr):
ret = False
if 'no_bias' in attr and (attr['no_bias'] == True... | 121 | 3,918 |
insightface | recognition/arcface_mxnet/common/rec2image.py | .py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import mxnet as mx
from mxnet import ndarray as nd
import random
import argparse
import cv2
import time
import sklearn
import numpy as np
def main(args):
include_datasets = args.includ... | 61 | 2,138 |
insightface | recognition/arcface_mxnet/common/build_eval_pack.py | .py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
#import mxnet as mx
#from mxnet import ndarray as nd
import argparse
import cv2
import pickle
import numpy as np
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'common')... | 137 | 4,483 |
insightface | recognition/arcface_mxnet/common/rec_builder.py | .py | import os
import sys
import mxnet as mx
from mxnet import ndarray as nd
import random
import argparse
import cv2
import time
import sklearn
import numpy as np
class SeqRecBuilder():
def __init__(self, path, image_size=(112, 112)):
self.path = path
self.image_size = image_size
self.last_lab... | 110 | 3,720 |
insightface | recognition/arcface_mxnet/common/face_align.py | .py | import cv2
import numpy as np
from skimage import transform as trans
src1 = np.array([[51.642, 50.115], [57.617, 49.990], [35.740, 69.007],
[51.157, 89.050], [57.025, 89.702]],
dtype=np.float32)
#<--left
src2 = np.array([[45.031, 50.118], [65.568, 50.872], [39.677, 68.111],
... | 72 | 2,274 |
insightface | recognition/arcface_mxnet/common/verification.py | .py | """Helper for evaluation on the Labeled Faces in the Wild dataset
"""
# MIT License
#
# Copyright (c) 2016 David Sandberg
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restricti... | 424 | 16,633 |
insightface | recognition/_evaluation_/megaface/gen_megaface.py | .py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from easydict import EasyDict as edict
import time
import sys
import numpy as np
import argparse
import struct
import cv2
import sklearn
from sklearn.preprocessing import normalize
import mxnet as mx... | 197 | 6,300 |
insightface | recognition/_evaluation_/megaface/remove_noises.py | .py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import datetime
import time
import shutil
import sys
import numpy as np
import argparse
import struct
import cv2
import mxnet as mx
from mxnet import ndarray as nd
feature_dim = 512
feature_ext = 1
... | 183 | 6,035 |
insightface | recognition/_evaluation_/ijb/ijb_1n.py | .py | #!/usr/bin/env python
# coding: utf-8
import os
import numpy as np
import timeit
import sklearn
import cv2
import sys
import argparse
import glob
import numpy.matlib
import heapq
import math
from datetime import datetime as dt
from sklearn import preprocessing
sys.path.append('./recognition')
from embedding import Emb... | 367 | 15,429 |
insightface | recognition/_evaluation_/ijb/ijb_11.py | .py | # coding: utf-8
import os
import numpy as np
#import cPickle
import pickle
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import timeit
import sklearn
import argparse
from sklearn.metrics import roc_curve, auc
from sklearn import preprocessing
import cv2
import sys
import g... | 381 | 13,355 |
insightface | recognition/_evaluation_/ijb/ijb_evals.py | .py | #!/usr/bin/env python3
import os
import cv2
import numpy as np
import pandas as pd
from tqdm import tqdm
from skimage import transform
from sklearn.preprocessing import normalize
from sklearn.metrics import roc_curve, auc
class Mxnet_model_interf:
def __init__(self, model_file, layer="fc1", image_size=(112, 112))... | 656 | 31,366 |
insightface | recognition/_evaluation_/ijb/ijb_onnx.py | .py | import argparse
import os
import pickle
import timeit
import cv2
import mxnet as mx
import numpy as np
import pandas as pd
import prettytable
import skimage.transform
from sklearn.metrics import roc_curve
from sklearn.preprocessing import normalize
import insightface
from insightface.model_zoo import ArcFaceONNX
SRC... | 268 | 10,264 |
insightface | recognition/_tools_/mask_renderer.py | .py | import os, sys, datetime
import numpy as np
import os.path as osp
import cv2
import insightface
from insightface.app import MaskRenderer
if __name__ == "__main__":
#make sure that you have download correct insightface model pack.
#make sure that BFM.mat and BFM_UV.mat have been generated
tool = MaskRender... | 22 | 606 |
insightface | recognition/subcenter_arcface/train_parall.py | .py | '''
@author: insightface
'''
import os
import sys
import math
import random
import logging
import pickle
import sklearn
import numpy as np
from image_iter import FaceImageIter
import mxnet as mx
from mxnet import ndarray as nd
import argparse
import mxnet.optimizer as optimizer
from config import config, default, gene... | 421 | 14,760 |
insightface | recognition/subcenter_arcface/image_iter.py | .py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import random
import logging
import sys
import numbers
import math
import sklearn
import datetime
import numpy as np
import cv2
from config import config
import mxnet as mx
from mxnet import ndarray ... | 313 | 11,419 |
insightface | recognition/subcenter_arcface/parall_module_local_v1.py | .py | '''
@author: insightface
'''
import logging
import copy
import time
import os
import mxnet as mx
import numpy as np
from mxnet import context as ctx
from mxnet.initializer import Uniform
from mxnet.module.base_module import BaseModule
from mxnet.module.module import Module
from mxnet import metric
from mxnet.model im... | 656 | 27,370 |
insightface | recognition/subcenter_arcface/drop.py | .py | import os
import shutil
import datetime
import sys
from mxnet import ndarray as nd
import mxnet as mx
import random
import argparse
import numbers
import cv2
import time
import pickle
import sklearn
import sklearn.preprocessing
from easydict import EasyDict as edict
import numpy as np
sys.path.append(os.path.join(os.pa... | 213 | 6,985 |
insightface | recognition/subcenter_arcface/sample_config.py | .py | import numpy as np
import os
from easydict import EasyDict as edict
config = edict()
config.bn_mom = 0.9
config.workspace = 256
config.emb_size = 512
config.ckpt_embedding = True
config.net_se = 0
config.net_act = 'prelu'
config.net_unit = 3
config.net_input = 1
config.net_blocks = [1, 4, 6, 2]
config.net_output = 'E... | 225 | 5,697 |
insightface | tools/onnx2caffe/convertCaffe.py | .py | #from __future__ import print_function
import sys
import caffe
import onnx
import numpy as np
from caffe.proto import caffe_pb2
caffe.set_mode_cpu()
from onnx2caffe._transformers import ConvAddFuser,ConstantsToInitializers
from onnx2caffe._graph import Graph
import onnx2caffe._operators as cvt
import onnx2caffe._weigh... | 115 | 3,363 |
insightface | tools/onnx2caffe/MyCaffe.py | .py | from collections import OrderedDict, Counter
from caffe.proto import caffe_pb2
from google import protobuf
import six
def param_name_dict():
"""Find out the correspondence between layer names and parameter names."""
layer = caffe_pb2.LayerParameter()
# get all parameter names (typically underscore case) ... | 126 | 4,773 |
insightface | tools/onnx2caffe/onnx2caffe/_error_utils.py | .py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import Dict, Text, Any, Callable
from ._graph import Node, Graph
class ErrorHandling(object):
'''
To handle errors and addition of custom layers
'''
def __init__(self,
add_c... | 65 | 2,026 |
insightface | tools/onnx2caffe/onnx2caffe/_weightloader.py | .py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
# from caffe import params as P
import numpy as np
from ._graph import Node, Graph
USE_DECONV_AS_UPSAMPLE = False
def _convert_conv(net, node, graph, err):
weight_na... | 163 | 5,656 |
insightface | tools/onnx2caffe/onnx2caffe/_graph.py | .py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from onnx import numpy_helper, ValueInfoProto, AttributeProto, GraphProto, NodeProto, TensorProto, TensorShapeProto
from typing import Any, Text, Iterable, List, Dict, Se... | 226 | 8,233 |
insightface | tools/onnx2caffe/onnx2caffe/_operators.py | .py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe import params as P
import math
import numpy as np
from ._graph import Node, Graph
from MyCaffe import Function as myf
USE_DECONV_AS_UPSAMPLE = False
def _comp... | 486 | 18,311 |
insightface | tools/onnx2caffe/onnx2caffe/_transformers.py | .py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from typing import Sequence, Text, Dict, List
import numpy as np
from onnx import TensorProto
from ._graph import Graph, Node
class NodesFuser(object):
'''
An... | 520 | 19,340 |
insightface | web-demos/src_recognition/main.py | .py | #!/usr/bin/env python
import os
import os.path as osp
import argparse
import cv2
import numpy as np
import onnxruntime
from scrfd import SCRFD
from arcface_onnx import ArcFaceONNX
onnxruntime.set_default_logger_severity(3)
assets_dir = osp.expanduser('~/.insightface/models/buffalo_l')
detector = SCRFD(os.path.join(... | 58 | 1,543 |
insightface | web-demos/src_recognition/arcface_onnx.py | .py | # -*- coding: utf-8 -*-
# @Organization : insightface.ai
# @Author : Jia Guo
# @Time : 2021-05-04
# @Function :
import numpy as np
import cv2
import onnx
import onnxruntime
import face_align
__all__ = [
'ArcFaceONNX',
]
class ArcFaceONNX:
def __init__(self, model_file=None, session=No... | 92 | 3,081 |
insightface | web-demos/src_recognition/face_align.py | .py | import cv2
import numpy as np
from skimage import transform as trans
src1 = np.array([[51.642, 50.115], [57.617, 49.990], [35.740, 69.007],
[51.157, 89.050], [57.025, 89.702]],
dtype=np.float32)
#<--left
src2 = np.array([[45.031, 50.118], [65.568, 50.872], [39.677, 68.111],
... | 142 | 4,586 |
insightface | web-demos/src_recognition/scrfd.py | .py |
from __future__ import division
import datetime
import numpy as np
#import onnx
import onnxruntime
import os
import os.path as osp
import cv2
import sys
def softmax(z):
assert len(z.shape) == 2
s = np.max(z, axis=1)
s = s[:, np.newaxis] # necessary step to do broadcasting
e_x = np.exp(z - s)
div =... | 330 | 12,637 |
insightface | cpp-package/inspireface/tools/output_error_table.py | .py | import click
import re
# Function to calculate the actual error code value based on the expressions
def calculate_error_code_value(error_code_str, error_definitions):
try:
# Replace the hex values and error definitions with actual values
error_code_str = re.sub(r'0X([0-9A-F]+)', lambda m: str(int(m... | 108 | 4,547 |
insightface | cpp-package/inspireface/tools/generate_error_tabel_to_python.py | .py | import click
import re
from datetime import datetime
# Function to calculate the actual error code value based on the expressions
def calculate_error_code_value(error_code_str, error_definitions):
try:
# Replace the hex values and error definitions with actual values
error_code_str = re.sub(r'0X([0... | 110 | 4,338 |
insightface | cpp-package/inspireface/tools/release_modelscope.py | .py | import os
import click
from modelscope.hub.api import HubApi
@click.command()
@click.option(
'--model-id',
default='tunmxy/InspireFace',
help='ModelScope model ID'
)
@click.option(
'--model-dir',
required=True,
type=click.Path(exists=True, file_okay=False, dir_okay=True),
help='Local mode... | 53 | 1,361 |
insightface | cpp-package/inspireface/tools/generate_release_models_info.py | .py | import hashlib
import os
import json
import click
need_models = [
"Pikachu",
"Megatron",
"Megatron_TRT",
"Gundam_RK356X",
"Gundam_RK3588",
]
def get_file_hash_sha256(file_path):
sha256 = hashlib.sha256()
with open(file_path, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):... | 50 | 1,464 |
insightface | cpp-package/inspireface/tools/transform_similarity_testing.py | .py | import numpy as np
import matplotlib.pyplot as plt
class SimilarityConverter:
def __init__(self,
threshold=0.48,
middle_score=0.6,
steepness=8.0,
output_range=(0.01, 0.99)):
self.threshold = threshold
self.middle_score = middl... | 104 | 3,994 |
insightface | cpp-package/inspireface/tools/get_model_md5.py | .py | import hashlib
import os
import click
file_list = [
"Pikachu",
"Megatron",
"Megatron_TRT",
"Gundam_RK356X",
"Gundam_RK3588",
]
def get_file_hash_sha256(file_path):
sha256 = hashlib.sha256()
with open(file_path, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
s... | 28 | 610 |
insightface | cpp-package/inspireface/tools/inspire_archive/archive_packing.py | .py | import os
import tarfile
import click
import tqdm
def remove_suffix(filename):
"""Remove the file suffix."""
return os.path.splitext(filename)[0]
@click.command()
@click.argument('folder_path')
@click.argument('output_filename')
@click.option('--rm-suffix', is_flag=True, default=True, help='Remove file suffix... | 48 | 1,839 |
insightface | cpp-package/inspireface/python/sample_face_track_from_video.py | .py | import time
import click
import cv2
import inspireface as isf
import numpy as np
import time
def generate_color(id):
"""
Generate a bright color based on the given integer ID. Ensures 50 unique colors.
Args:
id (int): The ID for which to generate a color.
Returns:
tuple: A tuple repr... | 165 | 6,319 |
insightface | cpp-package/inspireface/python/sample_face_recognition.py | .py | import os
import cv2
import inspireface as isf
import click
@click.command()
@click.argument('test_data_folder')
def case_face_recognition(test_data_folder):
"""
Launches the face recognition system, inserts face features into a database, and performs searches.
Args:
resource_path (str): Path to th... | 98 | 4,182 |
insightface | cpp-package/inspireface/python/sample_video.py | .py | import os
import cv2
import inspireface as isf
import numpy as np
import os
import cv2
def get_quality(image, session: isf.InspireFaceSession) -> float:
select_exec_func = isf.HF_ENABLE_QUALITY | isf.HF_ENABLE_MASK_DETECT | isf.HF_ENABLE_LIVENESS | isf.HF_ENABLE_INTERACTION | isf.HF_ENABLE_FACE_ATTRIBUTE
face... | 51 | 2,011 |
insightface | cpp-package/inspireface/python/setup.py | .py | from setuptools import setup, find_packages
from wheel.bdist_wheel import bdist_wheel
import platform
import subprocess
import os
def get_version():
"""Get version number"""
version_path = os.path.join(os.path.dirname(__file__), 'version.txt')
try:
with open(version_path, 'r') as f:
ret... | 152 | 4,883 |
insightface | cpp-package/inspireface/python/sample_face_comparison.py | .py | import cv2
import inspireface as isf
import click
@click.command()
@click.argument('image_path1')
@click.argument('image_path2')
def case_face_comparison(image_path1, image_path2):
"""
This is a sample application for comparing two face images.
Args:
image_path1 (str): Path to the first face image... | 53 | 1,812 |
insightface | cpp-package/inspireface/python/sample_feature_hub_crud.py | .py | import os
import inspireface as isf
import numpy as np
import os
import random
random.seed(43)
def gen_feature():
# Generate a random vector of length 512 and normalize it
vector = np.random.uniform(-1, 1, 512).astype(np.float32)
normalized_vector = vector / np.linalg.norm(vector)
return normalized_v... | 123 | 4,841 |
insightface | cpp-package/inspireface/python/pull_models.py | .py | import inspireface
for model in ["Pikachu", "Megatron"]:
inspireface.pull_latest_model(model)
| 5 | 99 |
insightface | cpp-package/inspireface/python/sample_feature_hub.py | .py | import os
import inspireface as isf
import numpy as np
import os
def case_feature_hub():
# Gen a random feature
gen = np.random.rand(512).astype(np.float32)
# Set db path
db_path = "test.db"
# Configure the feature management system.
feature_hub_config = isf.FeatureHubConfiguration(
pri... | 39 | 1,275 |
insightface | cpp-package/inspireface/python/sample_system_resource_statistics.py | .py |
import inspireface as isf
import click
@click.command()
@click.argument("resource_path")
def case_show_system_resource_statistics(resource_path):
"""
This case is used to test the system resource statistics.
"""
ret = isf.launch(resource_path)
assert ret, "Launch failure. Please ensure the res... | 37 | 1,077 |
insightface | cpp-package/inspireface/python/sample_face_detection.py | .py | import os
import cv2
import inspireface as isf
import click
race_tags = ["Black", "Asian", "Latino/Hispanic", "Middle Eastern", "White"]
gender_tags = ["Female", "Male"]
age_bracket_tags = [
"0-2 years old", "3-9 years old", "10-19 years old", "20-29 years old", "30-39 years old",
"40-49 years old", "50-59 yea... | 98 | 4,134 |
insightface | cpp-package/inspireface/python/read_nv21.py | .py | import cv2
import numpy as np
from inspireface import ImageStream
import inspireface as isf
def read_nv21(file_path, width, height, rotate=0):
with open(file_path, 'rb') as f:
nv21_data = f.read()
yuv = np.frombuffer(nv21_data, dtype=np.uint8)
expected_size = width * height * 3 // 2
... | 71 | 2,358 |
insightface | cpp-package/inspireface/python/inspireface/__init__.py | .py | from .modules import *
from .param import *
__version__ = version()
| 6 | 70 |
insightface | cpp-package/inspireface/python/inspireface/modules/__init__.py | .py | from .inspireface import ImageStream, FaceExtended, FaceInformation, SessionCustomParameter, InspireFaceSession, \
launch, terminate, FeatureHubConfiguration, feature_hub_enable, feature_hub_disable, feature_comparison, \
FaceIdentity, feature_hub_set_search_threshold, feature_hub_face_insert, SearchResult, \
... | 11 | 1,371 |
insightface | cpp-package/inspireface/python/inspireface/modules/exception.py | .py | from . import herror as errcode
from typing import Optional, Dict, Any
class InspireFaceError(Exception):
"""Base class for all InspireFace exceptions"""
def __init__(self, message: str, error_code: Optional[int] = None, **context):
super().__init__(message)
self.error_code = error_code
... | 243 | 7,490 |
insightface | cpp-package/inspireface/python/inspireface/modules/inspireface.py | .py | import ctypes
import numpy as np
from .core import *
from typing import Tuple, List
from dataclasses import dataclass
from loguru import logger
from .utils import ResourceManager
from .utils.resource import set_use_oss_download
from . import herror as errcode
# Exception system
from .exception import (
check_error... | 1,359 | 54,028 |
insightface | cpp-package/inspireface/python/inspireface/modules/core/native.py | .py | __docformat__ = "restructuredtext"
# Begin preamble for Python
import ctypes
import sys
from ctypes import * # noqa: F401, F403
import platform
from pathlib import Path
import subprocess
import os
def get_lib_path():
"""
Get the appropriate library path based on the current platform and architecture.
... | 2,350 | 95,097 |
insightface | cpp-package/inspireface/python/inspireface/modules/utils/resource.py | .py | """
InspireFace Resource Manager
This module provides model downloading functionality with two modes:
1. Original mode: Download models from COS (Tencent Cloud Object Storage)
2. ModelScope mode: Download models from ModelScope platform
ModelScope mode usage:
rm = ResourceManager(use_modelscope=True, modelscope_m... | 269 | 10,946 |
insightface | cpp-package/inspireface/python/test/test_settings.py | .py | import os
import sys
import inspireface as ifac
# ++ OPTIONAL ++
# Enabling will run all the benchmark tests, which takes time
ENABLE_BENCHMARK_TEST = True
# Enabling will run all the CRUD tests, which will take time
ENABLE_CRUD_TEST = False
# Enabling will run the face search benchmark, which takes time and must b... | 68 | 2,060 |
insightface | cpp-package/inspireface/python/test/test_utilis.py | .py | from test.test_settings import *
import inspireface as ifac
from inspireface.param import *
import numpy as np
import time
from functools import wraps
import cv2
from itertools import cycle
from tqdm import tqdm
from unittest import skipUnless as optional
def title(name: str = None):
print("--" * 35)
print(f... | 280 | 9,472 |
insightface | cpp-package/inspireface/python/test/performance/test_lfw_precision.py | .py | from test import *
import unittest
import cv2
@optional(ENABLE_LFW_PRECISION_TEST, "LFW dataset precision tests have been closed.")
class LFWPrecisionTestCase(unittest.TestCase):
def setUp(self) -> None:
self.quick = QuickComparison()
def test_lfw_precision(self):
pairs_path = os.path.join(L... | 60 | 2,302 |
insightface | cpp-package/inspireface/python/test/unit/test_recognition_module.py | .py | import unittest
from test import *
import inspireface as ifac
from inspireface.param import *
import cv2
class FaceRecognitionBaseCase(unittest.TestCase):
"""
This case is mainly used to test the basic functions of face recognition.
"""
def setUp(self) -> None:
# Prepare material
trac... | 224 | 9,490 |
insightface | cpp-package/inspireface/python/test/unit/test_tracker_module.py | .py | import unittest
from test import *
import inspireface as ifac
from inspireface.param import *
import cv2
class FaceTrackerCase(unittest.TestCase):
def setUp(self) -> None:
# Prepare material
track_mode = HF_DETECT_MODE_ALWAYS_DETECT
self.engine = ifac.InspireFaceSession(param=ifac.Session... | 131 | 5,338 |
insightface | cpp-package/inspireface/python/test/unit/test_base_module.py | .py | from test import *
import unittest
import inspireface as ifac
from inspireface.param import *
import cv2
class CameraStreamCase(unittest.TestCase):
def setUp(self) -> None:
"""Shared area for priority execution"""
pass
def test_image_codec(self) -> None:
image = cv2.imread(get_test_da... | 52 | 2,526 |
insightface | challenges/iccv21-mfr/mxnet_to_ort.py | .py | import sys
import os
import argparse
import onnx
import mxnet as mx
from onnx import helper
from onnx import TensorProto
from onnx import numpy_helper
print('mxnet version:', mx.__version__)
print('onnx version:', onnx.__version__)
assert mx.__version__ >= '1.8', 'mxnet version should >= 1.8'
assert onnx.__version__ ... | 116 | 3,463 |
insightface | challenges/iccv21-mfr/onnx_helper.py | .py | from __future__ import division
import datetime
import os
import os.path as osp
import glob
import numpy as np
import cv2
import sys
import onnxruntime
import onnx
import argparse
from onnx import numpy_helper
from insightface.data import get_image
class ArcFaceORT:
def __init__(self, model_path, cpu=False):
... | 254 | 10,397 |
insightface | challenges/iccv21-mfr/dataset_mask.py | .py | import numbers
import os
import queue as Queue
import threading
import mxnet as mx
import numpy as np
import torch
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
import cv2
import albumentations as A
from albumentations.pytorch import ToTensorV2
from insightface.app import MaskAugm... | 209 | 7,445 |
insightface | challenges/iccv19-lfr/gen_image_feature.py | .py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from datetime import datetime
import os.path
from easydict import EasyDict as edict
import time
import json
import sys
import numpy as np
import importlib
import itertools
import argparse
import stru... | 158 | 4,771 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.