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
python-package/insightface/thirdparty/face3d/morphable_model/load.py
.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import scipy.io as sio ### --------------------------------- load BFM data def load_BFM(model_path): ''' load BFM 3DMM model Args: model_path: path to BFM model. Return...
111
3,765
insightface
python-package/insightface/thirdparty/face3d/morphable_model/fit.py
.py
''' Estimating parameters about vertices: shape para, exp para, pose para(s, R, t) ''' import numpy as np from .. import mesh ''' TODO: a clear document. Given: image_points, 3D Model, Camera Matrix(s, R, t2d) Estimate: shape parameters, expression parameters Inference: projected_vertices = s*P*R(mu + shape + ...
273
8,101
insightface
python-package/insightface/thirdparty/face3d/mesh_numpy/transform.py
.py
''' Functions about transforming mesh(changing the position: modify vertices). 1. forward: transform(transform, camera, project). 2. backward: estimate transform matrix from correspondences. Preparation knowledge: transform&camera model: https://cs184.eecs.berkeley.edu/lecture/transforms-2 Part I: camera geometry and ...
385
12,319
insightface
python-package/insightface/thirdparty/face3d/mesh_numpy/render.py
.py
''' functions about rendering mesh(from 3d obj to 2d image). only use rasterization render here. Note that: 1. Generally, render func includes camera, light, raterize. Here no camera and light(I write these in other files) 2. Generally, the input vertices are normalized to [-1,1] and cetered on [0, 0]. (in world space)...
287
10,426
insightface
python-package/insightface/thirdparty/face3d/mesh_numpy/io.py
.py
''' io: read&write mesh 1. read obj as array(TODO) 2. write arrays to obj Preparation knowledge: representations of 3d face: mesh, point cloud... storage format: obj, ply, bin, asc, mat... ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as...
170
5,842
insightface
python-package/insightface/thirdparty/face3d/mesh_numpy/vis.py
.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import matplotlib.pyplot as plt from skimage import measure from mpl_toolkits.mplot3d import Axes3D def plot_mesh(vertices, triangles, subplot = [1,1,1], title = 'mesh', el = 90, az = -90, l...
25
791
insightface
python-package/insightface/thirdparty/face3d/mesh_numpy/light.py
.py
''' Functions about lighting mesh(changing colors/texture of mesh). 1. add light to colors/texture (shade each vertex) 2. fit light according to colors/texture & image. Preparation knowledge: lighting: https://cs184.eecs.berkeley.edu/lecture/pipeline spherical harmonics in human face: '3D Face Reconstruction from a Si...
216
7,502
insightface
python-package/insightface/thirdparty/face3d/mesh/transform.py
.py
''' Functions about transforming mesh(changing the position: modify vertices). 1. forward: transform(transform, camera, project). 2. backward: estimate transform matrix from correspondences. Author: Yao Feng Mail: yaofeng1995@gmail.com ''' from __future__ import absolute_import from __future__ import division from _...
383
12,207
insightface
python-package/insightface/thirdparty/face3d/mesh/render.py
.py
''' functions about rendering mesh(from 3d obj to 2d image). only use rasterization render here. Note that: 1. Generally, render func includes camera, light, raterize. Here no camera and light(I write these in other files) 2. Generally, the input vertices are normalized to [-1,1] and cetered on [0, 0]. (in world space)...
136
4,597
insightface
python-package/insightface/thirdparty/face3d/mesh/io.py
.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import os from skimage import io from time import time from .cython import mesh_core_cython ## TODO ## TODO: c++ version def read_obj(obj_name): ''' read mesh ''' return 0 # -----------...
142
4,938
insightface
python-package/insightface/thirdparty/face3d/mesh/light.py
.py
''' Functions about lighting mesh(changing colors/texture of mesh). 1. add light to colors/texture (shade each vertex) 2. fit light according to colors/texture & image. ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from .cython impo...
214
7,492
insightface
python-package/insightface/thirdparty/face3d/mesh/cython/setup.py
.py
''' python setup.py build_ext -i to compile ''' # setup.py from distutils.core import setup, Extension from Cython.Build import cythonize from Cython.Distutils import build_ext import numpy setup( name = 'mesh_core_cython', cmdclass={'build_ext': build_ext}, ext_modules=[Extension("mesh_core_cython", ...
21
472
insightface
python-package/insightface/commands/rec_add_mask_param.py
.py
import numbers import os from argparse import ArgumentParser, Namespace import numpy as np from . import BaseInsightFaceCLICommand def rec_add_mask_param_command_factory(args: Namespace): return RecAddMaskParamCommand( args.input, args.output ) class RecAddMaskParamCommand(BaseInsightFaceCLIComm...
108
3,878
insightface
python-package/insightface/commands/insightface_cli.py
.py
#!/usr/bin/env python from argparse import ArgumentParser from .model_download import ModelDownloadCommand from .rec_add_mask_param import RecAddMaskParamCommand def main(): parser = ArgumentParser("InsightFace CLI tool", usage="insightface-cli <command> [<args>]") commands_parser = parser.add_subparsers(hel...
30
724
insightface
python-package/insightface/commands/__init__.py
.py
from abc import ABC, abstractmethod from argparse import ArgumentParser class BaseInsightFaceCLICommand(ABC): @staticmethod @abstractmethod def register_subcommand(parser: ArgumentParser): raise NotImplementedError() @abstractmethod def run(self): raise NotImplementedError()
14
315
insightface
python-package/insightface/commands/model_download.py
.py
from argparse import ArgumentParser from . import BaseInsightFaceCLICommand import os import os.path as osp import zipfile import glob from ..utils import download def model_download_command_factory(args): return ModelDownloadCommand(args.model, args.root, args.force) class ModelDownloadCommand(BaseInsightFace...
37
1,236
insightface
python-package/insightface/app/mask_renderer.py
.py
import os, sys, datetime import numpy as np import os.path as osp import albumentations as A from albumentations.core.transforms_interface import ImageOnlyTransform from .face_analysis import FaceAnalysis from ..utils import get_model_dir from ..thirdparty import face3d from ..data import get_image as ins_get_image fro...
233
9,846
insightface
python-package/insightface/app/__init__.py
.py
from .face_analysis import * try: import os os.environ.setdefault("NO_ALBUMENTATIONS_UPDATE", "1") from .mask_renderer import * except ImportError: # The mask renderer depends on optional compiled face3d extensions. Keep the # main InsightFace API importable in source-tree and GUI-safe environments...
11
331
insightface
python-package/insightface/app/face_analysis.py
.py
# -*- coding: utf-8 -*- # @Organization : insightface.ai # @Author : Jia Guo # @Time : 2021-05-04 # @Function : from __future__ import division import glob import os.path as osp import numpy as np import onnxruntime from numpy.linalg import norm from ..model_zoo import model_zoo from ..utils...
128
4,876
insightface
python-package/insightface/app/common.py
.py
import numpy as np from numpy.linalg import norm as l2norm class Face(dict): def __init__(self, d=None, **kwargs): if d is None: d = {} if kwargs: d.update(**kwargs) for k, v in d.items(): setattr(self, k, v) # Class attributes #for k in ...
49
1,436
insightface
python-package/packaging/desktop/pyinstaller_entry.py
.py
from insightface.gui.__main__ import main if __name__ == "__main__": raise SystemExit(main())
6
100
insightface
python-package/tests/gui/test_gui_smoke.py
.py
import pytest import os from pathlib import Path import numpy as np def test_main_window_smoke(tmp_path): os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") PySide6 = pytest.importorskip("PySide6") from PySide6.QtCore import QEvent, QUrl, Qt from PySide6.QtWidgets import QAbstractItemView, QApplica...
280
15,026
insightface
python-package/tests/gui/test_providers.py
.py
from insightface.gui.core import face_engine def test_cuda_choice_falls_back_when_provider_is_unavailable(monkeypatch): monkeypatch.setattr(face_engine, "available_execution_providers", lambda: ["CPUExecutionProvider"]) assert face_engine.is_cuda_provider_available() is False assert face_engine.providers...
22
878
insightface
python-package/tests/gui/test_links.py
.py
import pytest def test_insightface_links_add_gui_referrer(): pytest.importorskip("PySide6") from insightface.gui.core.links import add_gui_referrer url = add_gui_referrer("https://www.insightface.ai/contact", content="license_enterprise_support") assert url.startswith("https://www.insightface.ai/co...
25
788
insightface
python-package/tests/gui/test_storage.py
.py
import numpy as np from insightface.gui.core.storage import Storage from insightface.gui.core.utils import encode_webp_thumbnail def test_storage_people_samples_and_search(tmp_path): db = tmp_path / "test.db" storage = Storage(db) person_id = storage.add_person("Alice") emb = np.array([1.0, 0.0, 0.0]...
92
3,159
insightface
python-package/tests/gui/test_theme.py
.py
from insightface.gui.core.theme import ( THEME_OPTIONS, application_stylesheet, effective_theme, normalize_theme, theme_description, theme_label, ) def test_theme_options_include_multiple_product_themes(): values = [option.value for option in THEME_OPTIONS] assert values[0] == "system...
59
2,073
insightface
python-package/tests/gui/test_quality.py
.py
import numpy as np from insightface.gui.core.quality import blur_score, score_face def test_quality_range_and_blur(): image = np.full((120, 120, 3), 128, dtype=np.uint8) image[40:80, 40:80] = 255 assert blur_score(image) >= 0 score, flags = score_face(image, [30, 30, 90, 90], det_score=0.9) asser...
13
377
insightface
python-package/tests/gui/test_reporting.py
.py
from pathlib import Path import pytest from insightface.gui.core.models import EvaluationResult from insightface.gui.core.reporting import generate_html_report, generate_markdown_report, write_reports def _result(): return EvaluationResult( scenario="KYC / 1:1 Verification", model_name="buffalo_...
75
2,490
insightface
python-package/tests/gui/test_model_downloads.py
.py
from insightface.gui.core.model_downloads import GFPGAN_DOWNLOAD_URL, _content_range_total, fallback_model_assets, local_model_status from insightface.gui.core.paths import default_workspace, workspace_paths def test_default_gui_workspace_path(): workspace = default_workspace() assert workspace.name == "gui" ...
43
1,890
insightface
python-package/tests/gui/test_similarity.py
.py
import numpy as np from insightface.gui.core.recognition import cosine_similarity, normalize_embedding, search_gallery def test_similarity_and_topk(): emb = normalize_embedding(np.array([3.0, 4.0], dtype=np.float32)) assert np.allclose(np.linalg.norm(emb), 1.0) assert cosine_similarity([1, 0], [1, 0]) ==...
18
825
insightface
python-package/tests/gui/test_clustering.py
.py
import numpy as np from insightface.gui.core.clustering import cluster_embeddings_dbscan def test_dbscan_default_distance_threshold_groups_near_faces(): embeddings = [ np.array([1.0, 0.0], dtype=np.float32), np.array([0.98, 0.08], dtype=np.float32), np.array([0.0, 1.0], dtype=np.float32),...
62
1,993
insightface
python-package/tests/gui/test_i18n.py
.py
import os import pytest os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") from insightface.gui.core.i18n import ( LANGUAGE_OPTIONS, effective_language, normalize_language, tr, ) def test_supported_languages_match_homepage_language_set(): values = {option.value for option in LANGUAGE_OPTIONS...
181
6,644
insightface
python-package/tests/gui/test_qt_plugins.py
.py
import os import sys from pathlib import Path import pytest def _platform_plugin_names(): if sys.platform == "darwin": return {"libqcocoa.dylib", "libqoffscreen.dylib"} if sys.platform.startswith("win"): return {"qwindows.dll", "qoffscreen.dll"} if sys.platform.startswith("linux"): ...
60
2,033
insightface
python-package/tests/gui/test_navigation.py
.py
import os from insightface.gui.core.config import AppConfig, load_config, save_config from insightface.gui.core.navigation import AppMode, GLOBAL_PAGE_TITLES, NAVIGATION_MODES def test_navigation_modes_do_not_include_global_sidebar_items(): assert set(NAVIGATION_MODES) == set(AppMode) all_page_keys = [] ...
99
3,257
insightface
python-package/tests/gui/test_swap.py
.py
import numpy as np from insightface.gui.core.swap import GFPGANRestorer class _FakeSession: def __init__(self): self.input_shape = None def run(self, output_names, inputs): del output_names tensor = next(iter(inputs.values())) self.input_shape = tensor.shape return [n...
28
771
insightface
python-package/tests/gui/test_cli.py
.py
from insightface.gui.__main__ import main from insightface.gui.app import create_context from insightface.gui.core.config import AppConfig, save_config def test_cli_import_and_version(capsys): import insightface import insightface.gui assert insightface.__version__ == "1.0.1" assert insightface.gui._...
41
1,199
insightface
python-package/tests/gui/test_detector_det_size.py
.py
from insightface.app import FaceAnalysis from insightface.model_zoo import model_zoo from insightface.model_zoo.retinaface import RetinaFace from insightface.model_zoo.scrfd import DEFAULT_DET_SIZES, SCRFD from insightface.gui.core.face_engine import FaceEngine def test_scrfd_accepts_multi_det_size_config(): asse...
88
2,837
insightface
python-package/tests/gui/test_enterprise_evaluation.py
.py
from pathlib import Path import numpy as np from insightface.gui.core.evaluation import ( MULTI_FACE_REQUIRE_ONE, MULTI_FACE_SKIP, MULTI_FACE_USE_CENTERED_LARGEST, MULTI_FACE_USE_LARGEST, _select_face_from_faces, _tar_far_from_scores, run_identity_identification_evaluation, run_identit...
284
8,548
insightface
reconstruction/PBIDR/code/preprocess/get_aux_dataset.py
.py
import os import sys sys.path.append(os.path.abspath('')) import torch import argparse import numpy as np from pytorch3d.io import load_objs_as_meshes, save_obj,load_obj from pytorch3d.renderer import ( look_at_view_transform, PerspectiveCameras, # FoVPerspectiveCameras, PointLights, # DirectionalLi...
158
6,404
insightface
reconstruction/PBIDR/code/preprocess/preprocess_cameras.py
.py
import numpy as np import matplotlib.image as mpimg import matplotlib.pyplot as plt import cv2 import argparse from glob import glob import os import sys import pickle sys.path.append('../code') from scipy.spatial.transform import Rotation import utils.general as utils def get_Ps_from_Faces(R, T): Ps = [] cam...
100
3,363
insightface
reconstruction/PBIDR/code/datasets/dataset.py
.py
import os import torch import numpy as np import utils.general as utils from utils import rend_util class IFDataset(torch.utils.data.Dataset): """Dataset for a class of objects, where each datapoint is a SceneInstanceDataset.""" def __init__(self, train_cameras, data_dir, ...
155
5,822
insightface
reconstruction/PBIDR/code/evaluation/eval.py
.py
import sys sys.path.append('../code') import argparse import GPUtil import os from pyhocon import ConfigFactory import torch import numpy as np import cvxpy as cp from PIL import Image import math import utils.general as utils import utils.plots as plt from utils import rend_util def evaluate(**kwargs): torch.set...
212
9,657
insightface
reconstruction/PBIDR/code/model/renderer.py
.py
import torch import torch.nn as nn import numpy as np import trimesh import os from utils import rend_util from model.embedder import * from model.ray_tracing import RayTracing from model.sample_network import SampleNetwork def barycentric_coordinates(p, select_vertices): a = select_vertices[:, 0, :] b = se...
461
17,023
insightface
reconstruction/PBIDR/code/model/sample_network.py
.py
import torch.nn as nn import torch class SampleNetwork(nn.Module): ''' Represent the intersection (sample) point as differentiable function of the implicit geometry and camera parameters. See equation 3 in the paper for more details. ''' def forward(self, surface_output, surface_sdf_values, surfac...
21
900
insightface
reconstruction/PBIDR/code/model/ray_tracing.py
.py
import torch import torch.nn as nn from utils import rend_util class RayTracing(nn.Module): def __init__( self, object_bounding_sphere=1.0, sdf_threshold=5.0e-5, line_search_step=0.5, line_step_iters=1, sphere_tracing_iters=10, n_s...
302
15,667
insightface
reconstruction/PBIDR/code/model/embedder.py
.py
import torch """ Positional encoding embedding. Code was taken from https://github.com/bmild/nerf. """ class Embedder: def __init__(self, **kwargs): self.kwargs = kwargs self.create_embedding_fn() def create_embedding_fn(self): embed_fns = [] d = self.kwargs['input_dims'] ...
51
1,521
insightface
reconstruction/PBIDR/code/model/loss.py
.py
import torch from torch import nn from torch.nn import functional as F class IFLoss(nn.Module): def __init__(self, eikonal_weight, mask_weight, reg_weight, normal_weight, alpha): super().__init__() self.eikonal_weight = eikonal_weight self.mask_weight = mask_weight self.reg_weight =...
70
3,017
insightface
reconstruction/PBIDR/code/utils/rend_util.py
.py
import numpy as np import imageio import skimage import cv2 import torch from torch.nn import functional as F def load_rgb(path): img = imageio.imread(path) img = skimage.img_as_float32(img) # pixel values between [-1,1] img -= 0.5 img *= 2. img = img.transpose(2, 0, 1) return img def loa...
193
6,023
insightface
reconstruction/PBIDR/code/utils/general.py
.py
import os from glob import glob import torch def mkdir_ifnotexists(directory): if not os.path.exists(directory): os.mkdir(directory) def get_class(kls): parts = kls.split('.') module = ".".join(parts[:-1]) m = __import__(module) for comp in parts[1:]: m = getattr(m, comp) retur...
66
2,338
insightface
reconstruction/PBIDR/code/utils/plots.py
.py
import plotly.graph_objs as go import plotly.offline as offline import numpy as np import torch from skimage import measure import torchvision import trimesh from PIL import Image from utils import rend_util import pickle def plot_latent(model, latent, indices, model_outputs ,pose, rgb_gt, path, epoch, img_res, plot_...
424
17,365
insightface
reconstruction/PBIDR/code/training/train.py
.py
import os from datetime import datetime from pyhocon import ConfigFactory import sys import torch import torch.nn as nn import utils.general as utils import utils.plots as plt class IFTrainRunner(): def __init__(self,**kwargs): torch.set_default_dtype(torch.float32) torch.set_num_threads(1) ...
284
13,809
insightface
reconstruction/PBIDR/code/training/runner.py
.py
import sys sys.path.append('../code') import argparse import GPUtil import torch import random import numpy as np from training.train import IFTrainRunner def setup_seed(seed): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) random.seed(seed) torch.backends.cudnn.det...
59
2,629
insightface
reconstruction/gaze/models.py
.py
import pytorch_lightning as pl from pytorch_lightning.callbacks import ModelCheckpoint from pytorch_lightning.callbacks import LearningRateMonitor from pytorch_lightning.loggers import TensorBoardLogger import torch import torch.nn as nn import timm class GazeModel(pl.LightningModule): def __init__(self, backbone,...
76
2,698
insightface
reconstruction/gaze/test_gaze.py
.py
from models import GazeModel import sys import glob import torch import os import os.path as osp import numpy as np import cv2 import os.path as osp import insightface from insightface.app import FaceAnalysis from insightface.utils import face_align import menpo.io as mio from menpo.image import Image from menpo.shape...
240
8,943
insightface
reconstruction/gaze/trainer_gaze.py
.py
from argparse import ArgumentParser import os import os.path as osp import torch import torch.nn as nn from torch.nn import functional as F from torch.utils.data import DataLoader import pytorch_lightning as pl from pytorch_lightning.callbacks import ModelCheckpoint from pytorch_lightning.callbacks import LearningRate...
90
2,761
insightface
reconstruction/gaze/datasets/dataset_gaze.py
.py
import os import os.path as osp import queue as Queue import mxnet as mx import pickle import threading import logging import numpy as np import insightface from insightface.utils import face_align import torch from torch.utils.data import DataLoader, Dataset from torchvision import transforms import cv2 import albumen...
185
6,703
insightface
reconstruction/gaze/datasets/augs.py
.py
import numpy as np import albumentations as A from albumentations.core.transforms_interface import ImageOnlyTransform class RectangleBorderAugmentation(ImageOnlyTransform): def __init__( self, fill_value = 0, limit = 0.3, always_apply=False, p=1.0, ...
41
1,332
insightface
reconstruction/jmlr/eye_dataset.py
.py
import os import os.path as osp import numpy as np import menpo.io as mio def project_shape_in_image(verts, R_t, M_proj, M1): verts_homo = verts if verts_homo.shape[1] == 3: ones = np.ones([verts_homo.shape[0], 1]) verts_homo = np.concatenate([verts_homo, ones], axis=1) verts_out = verts_h...
72
2,884
insightface
reconstruction/jmlr/losses.py
.py
import torch from torch import nn import torch.nn.functional as F import kornia import numpy as np #def loss_l1(a, b): #_loss = torch.abs(a - b) #_loss = torch.mean(_loss, dim=1) ##if epoch>4 and cfg.loss_hard: ## _loss, _ = torch.topk(_loss, k=int(cfg.batch_size*0.3)) #_loss = torch.mean(_loss)...
112
4,223
insightface
reconstruction/jmlr/train.py
.py
import argparse import logging import os import time import timm import glob import numpy as np import os.path as osp import torch import torch.distributed as dist from torch import nn import torch.nn.functional as F import torch.utils.data.distributed from torch.nn.utils import clip_grad_norm_ from dataset import Fac...
304
10,804
insightface
reconstruction/jmlr/flops.py
.py
from ptflops import get_model_complexity_info import os import argparse from utils.utils_config import get_config from backbones import get_network if __name__ == '__main__': parser = argparse.ArgumentParser(description='JMLR FLOPs') parser.add_argument('config', type=str, help='input config file') args =...
26
927
insightface
reconstruction/jmlr/rec_builder.py
.py
import pickle import numpy as np import os import os.path as osp import glob import argparse import cv2 import time import datetime import pickle import sklearn import mxnet as mx from utils.utils_config import get_config from dataset import FaceDataset, Rt26dof class RecBuilder(): def __init__(self, path, image_s...
136
4,944
insightface
reconstruction/jmlr/inference_simple.py
.py
import os import time import timm import glob import numpy as np import os.path as osp import cv2 import torch import torch.distributed as dist from torch import nn from pathlib import Path from backbones import get_network from skimage import transform as sktrans from scipy.spatial.transform import Rotation def bat...
323
11,775
insightface
reconstruction/jmlr/lr_scheduler.py
.py
import torch from torch.optim.lr_scheduler import _LRScheduler class PolyScheduler(_LRScheduler): def __init__(self, optimizer, base_lr, max_steps, warmup_steps, last_epoch=-1): self.base_lr = base_lr self.warmup_...
94
3,225
insightface
reconstruction/jmlr/gen_dataset_meta.py
.py
import pickle import numpy as np import os import os.path as osp import glob import argparse import cv2 import time import datetime import pickle import sklearn import mxnet as mx from utils.utils_config import get_config from dataset import MXFaceDataset, Rt26dof if __name__ == "__main__": cfg = get_config('confi...
36
1,032
insightface
reconstruction/jmlr/validate_dist.py
.py
from dataset import FaceDataset, DataLoaderX, MXFaceDataset import argparse import logging import os import time import timm import glob import numpy as np import os.path as osp from utils.utils_config import get_config from scipy.spatial.transform import Rotation import torch import torch.distributed as dist from tor...
187
8,092
insightface
reconstruction/jmlr/dataset.py
.py
import numbers import os import os.path as osp import pickle import queue as Queue import threading import logging import numbers import math import pandas as pd from scipy.spatial.transform import Rotation import mxnet as mx from pathlib import Path import numpy as np import torch from torch.utils.data import DataLoa...
812
33,526
insightface
reconstruction/jmlr/augs.py
.py
import numpy as np import cv2 import os import os.path as osp import albumentations as A from albumentations.core.transforms_interface import ImageOnlyTransform from albumentations.pytorch import ToTensorV2 class RectangleBorderAugmentation(ImageOnlyTransform): def __init__( self, fill_val...
272
10,387
insightface
reconstruction/jmlr/backbones/resnet.py
.py
"""PyTorch ResNet This started as a copy of https://github.com/pytorch/vision 'resnet.py' (BSD-3-Clause) with additional dropout and dynamic global avg/max pool. ResNeXt, SE-ResNeXt, SENet, and MXNet Gluon stem/downsample variants, tiered stems added by Ross Wightman Copyright 2019, Ross Wightman """ import math fro...
454
18,960
insightface
reconstruction/jmlr/backbones/network.py
.py
import os import time import timm import glob import numpy as np import os.path as osp import torch import torch.distributed as dist from torch import nn import torch.nn.functional as F from .iresnet import get_model as arcface_get_model def kaiming_leaky_init(m): classname = m.__class__.__name__ if classnam...
261
9,250
insightface
reconstruction/jmlr/backbones/iresnet.py
.py
import torch from torch import nn import torch.nn.functional as F import logging __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, ...
327
13,303
insightface
reconstruction/jmlr/utils/plot.py
.py
# coding: utf-8 import os from pathlib import Path import matplotlib.pyplot as plt import numpy as np import pandas as pd from menpo.visualize.viewmatplotlib import sample_colours_from_colourmap from prettytable import PrettyTable from sklearn.metrics import roc_curve, auc image_path = "/data/anxiang/IJB_release/IJB...
73
2,222
insightface
reconstruction/jmlr/utils/utils_amp.py
.py
from typing import Dict, List import torch #from torch._six import container_abcs import collections.abc as 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 __i...
83
3,229
insightface
reconstruction/jmlr/utils/utils_logging.py
.py
import logging import os import sys class AverageMeter(object): """Computes and stores the average and current value """ def __init__(self): self.val = None self.avg = None self.sum = None self.count = None self.reset() def reset(self): self.val = 0 ...
41
1,081
insightface
reconstruction/jmlr/utils/utils_callbacks.py
.py
import logging import os import time from typing import List import torch import psutil #from eval import verification #from partial_fc import PartialFC #from torch2onnx import convert_onnx from utils.utils_logging import AverageMeter class CallBackVerification(object): def __init__(self, frequent, rank, val_ta...
130
5,429
insightface
reconstruction/jmlr/utils/utils_config.py
.py
import importlib import os import os.path as osp import numpy as np 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] #print('A:', confi...
28
934
insightface
reconstruction/jmlr/configs/s1.py
.py
from easydict import EasyDict as edict config = edict() config.dataset = "wcpa" config.root_dir = '/data/insightface/wcpa' config.cache_dir = './cache_align' #config.num_classes = 617970 #config.num_classes = 2000000 #config.num_classes = 80000000 #config.val_targets = ["lfw", "cfp_fp", "agedb_30"] #config.val_target...
55
1,227
insightface
reconstruction/jmlr/configs/s2.py
.py
from easydict import EasyDict as edict config = edict() config.dataset = "wcpa" config.root_dir = '/data/insightface/wcpa' config.cache_dir = './cache_align_eyes' #config.num_classes = 617970 #config.num_classes = 2000000 #config.num_classes = 80000000 #config.val_targets = ["lfw", "cfp_fp", "agedb_30"] #config.val_t...
58
1,298
insightface
reconstruction/jmlr/configs/base.py
.py
from easydict import EasyDict as edict import numpy as np config = edict() config.embedding_size = 512 config.sample_rate = 1 config.fp16 = 0 config.tf32 = False config.backbone_wd = None config.batch_size = 128 config.clip_grad = None config.dropout = 0.0 #config.warmup_epoch = -1 config.loss = 'cosface' config.margi...
106
2,604
insightface
reconstruction/ostec/run_ostec.py
.py
# Copyright (c) 2020, Baris Gecer. All rights reserved. # # This work is made available under the CC BY-NC-SA 4.0. # To view a copy of this license, see LICENSE import time import os import glob from random import shuffle import argparse from argparse import Namespace import menpo.io as mio import menpo.image import c...
94
3,826
insightface
reconstruction/ostec/core/generator_model.py
.py
# Copyright (c) 2020, Baris Gecer. All rights reserved. # # This work is made available under the CC BY-NC-SA 4.0. # To view a copy of this license, see LICENSE import math import tensorflow as tf import numpy as np import external.stylegan2.dnnlib.tflib as tflib from functools import partial def create_stub(name, b...
142
7,228
insightface
reconstruction/ostec/core/projection_handler.py
.py
# Copyright (c) 2020, Baris Gecer. All rights reserved. # # This work is made available under the CC BY-NC-SA 4.0. # To view a copy of this license, see LICENSE import os import argparse import pickle from tqdm.auto import tqdm import PIL.Image from PIL import ImageFilter import numpy as np import external.stylegan2.d...
200
9,991
insightface
reconstruction/ostec/core/landmark_handler.py
.py
# Copyright (c) 2020, Baris Gecer. All rights reserved. # # This work is made available under the CC BY-NC-SA 4.0. # To view a copy of this license, see LICENSE import tensorflow as tf from external.landmark_detector import networks from external.landmark_detector.flags import FLAGS def tf_heatmap_to_lms(heatmap): ...
36
1,378
insightface
reconstruction/ostec/core/perceptual_model.py
.py
# Copyright (c) 2020, Baris Gecer. All rights reserved. # # This work is made available under the CC BY-NC-SA 4.0. # To view a copy of this license, see LICENSE from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf import bz2 import PIL.Image from PIL import ImageFi...
305
16,023
insightface
reconstruction/ostec/core/config.py
.py
# Copyright (c) 2020, Baris Gecer. All rights reserved. # # This work is made available under the CC BY-NC-SA 4.0. # To view a copy of this license, see LICENSE import argparse def split_to_batches(l, n): for i in range(0, len(l), n): yield l[i:i + n] def str2bool(v): if isinstance(v, bool): r...
96
7,976
insightface
reconstruction/ostec/core/operator.py
.py
# Copyright (c) 2020, Baris Gecer. All rights reserved. # # This work is made available under the CC BY-NC-SA 4.0. # To view a copy of this license, see LICENSE from utils.align2stylegan import align_im2stylegan, align_mesh2stylegan from core.projection_handler import Projection_Handler from skimage.morphology import ...
436
20,184
insightface
reconstruction/ostec/core/arcface_handler.py
.py
# Copyright (c) 2020, Baris Gecer. All rights reserved. # # This work is made available under the CC BY-NC-SA 4.0. # To view a copy of this license, see LICENSE import tensorflow as tf import numpy as np from external import arcface50 from skimage import transform as trans def align_arcface(image, landmarks): ""...
117
4,585
insightface
reconstruction/ostec/utils/shading.py
.py
# Copyright (c) 2020, Baris Gecer. All rights reserved. # # This work is made available under the CC BY-NC-SA 4.0. # To view a copy of this license, see LICENSE """ Renders 3D faces in python with lambertian shading Author: Stylianos Ploumpis """ import numpy as np from menpo.transform import UniformScale, Transl...
66
2,274
insightface
reconstruction/ostec/utils/utils.py
.py
# Copyright (c) 2020, Baris Gecer. All rights reserved. # # This work is made available under the CC BY-NC-SA 4.0. # To view a copy of this license, see LICENSE import PIL.Image from skimage.morphology import binary_dilation, disk from skimage.filters import gaussian from scipy.interpolate import NearestNDInterpolato...
171
7,103
insightface
reconstruction/ostec/utils/generate_heatmap.py
.py
import numpy as np import math import cv2 # Adapted from: https://github.com/1adrianb/face-alignment/blob/master/face_alignment/utils.py def _gaussian(size=3, sigma=0.25, amplitude=1, normalize=False, width=None, height=None, sigma_horz=None, sigma_vert=None, mean_horz=0.5, mean_vert=0.5): """ Genera...
129
4,861
insightface
reconstruction/ostec/utils/ganfit_camera.py
.py
# Copyright (c) 2020, Baris Gecer. All rights reserved. # # This work is made available under the CC BY-NC-SA 4.0. # To view a copy of this license, see LICENSE import numpy as np import math """Collection of functions to adapt GANFit camera parameters""" GANFIT_CAMERA_CONSTANTS = [np.array([[0.0, 0.0, 6.0]], dtype=...
260
9,601
insightface
reconstruction/ostec/utils/image_rasterization.py
.py
# Copyright (c) 2020, Baris Gecer. All rights reserved. # # This work is made available under the CC BY-NC-SA 4.0. # To view a copy of this license, see LICENSE from menpo3d.rasterize import ( rasterize_barycentric_coordinate_images, rasterize_mesh_from_barycentric_coordinate_images) from menpo.transform impo...
70
2,946
insightface
reconstruction/ostec/utils/align2stylegan.py
.py
# Copyright (c) 2020, Baris Gecer. All rights reserved. # # This work is made available under the CC BY-NC-SA 4.0. # To view a copy of this license, see LICENSE import numpy as np import scipy.ndimage import PIL.Image def create_perspective_transform_matrix(src, dst): """ Creates a perspective transformation matr...
235
9,836
insightface
reconstruction/ostec/external/arcface50.py
.py
# Copyright (c) 2020, Baris Gecer. All rights reserved. # # This work is made available under the CC BY-NC-SA 4.0. # To view a copy of this license, see LICENSE import tensorflow as tf __weights_dict = dict() is_train = False def load_weights(weight_file): import numpy as np if weight_file == None: ...
298
27,626
insightface
reconstruction/ostec/external/landmark_detector/utils.py
.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf import menpo.io as mio from menpo.image import Image from menpo.shape import PointCloud import cv2 from tensorflow.python.framework import ops from tensorflow.python....
422
15,450
insightface
reconstruction/ostec/external/landmark_detector/models.py
.py
import tensorflow as tf import numpy as np slim = tf.contrib.slim # custom layers def deconv_layer(net, up_scale, n_channel, method='transpose'): nh = tf.shape(net)[-3] * up_scale nw = tf.shape(net)[-2] * up_scale if method == 'transpose': net = slim.conv2d_transpose(net, n_channel, (up_scale, u...
1,334
96,462
insightface
reconstruction/ostec/external/landmark_detector/networks.py
.py
import tensorflow as tf from external.landmark_detector import utils, models, data_provider from tensorflow.python.platform import tf_logging as logging slim = tf.contrib.slim from external.landmark_detector.flags import FLAGS # general framework class DeepNetwork(object): def __init__(self): pass ...
181
6,247
insightface
reconstruction/ostec/external/landmark_detector/flags.py
.py
import tensorflow as tf slim = tf.contrib.slim FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_float('initial_learning_rate', 0.0001, '''Initial learning rate.''') tf.app.flags.DEFINE_float('num_epochs_per_decay', 5.0, '''Epochs after which learning rate decays.''') tf.app.flags.DEFINE_float('learning_rate_decay_facto...
32
1,970
insightface
reconstruction/ostec/external/landmark_detector/data_provider.py
.py
import tensorflow as tf import numpy as np from menpo.transform import Translation from external.landmark_detector.flags import FLAGS def augment_img(img, augmentation): flip, rotate, rescale = np.array(augmentation).squeeze() rimg = img.rescale(rescale) rimg = rimg.rotate_ccw_about_centre(rotate) cr...
237
8,869
insightface
reconstruction/ostec/external/stylegan2/projector.py
.py
# Copyright (c) 2019, NVIDIA Corporation. All rights reserved. # # This work is made available under the Nvidia Source Code License-NC. # To view a copy of this license, visit # https://nvlabs.github.io/stylegan2/license.html import numpy as np import tensorflow as tf import dnnlib import dnnlib.tflib as tflib from t...
207
8,983