Skip to content

Support inference on MacOS with MPS or CPU and add face detection script #188

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
180 changes: 180 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# UV
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
#uv.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

# PyPI configuration file
.pypirc

*-bk
*_bk
*-bk*
*_bk*
*copy*

# MacOS
.DS_Store
78 changes: 71 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,16 +94,31 @@ conda env create -f environment.yml
source activate deep3d_pytorch
```

2. Install Nvdiffrast library:
```
git clone -b 0.3.0 https://github.com/NVlabs/nvdiffrast
cd nvdiffrast # ./Deep3DFaceRecon_pytorch/nvdiffrast
pip install .
```
2. Install mesh renderer:
1. Nvdiffrast library (necessary for training, optional for testing):
```
git clone -b 0.3.0 https://github.com/NVlabs/nvdiffrast
cd nvdiffrast # ./Deep3DFaceRecon_pytorch/nvdiffrast
pip install .
cd .. # ./Deep3DFaceRecon_pytorch
```
2. Use a cpu renderer from 3DDFA-V3 instead for testing (which can work on MacOS):
```
git clone --depth=1 https://github.com/wang-zidu/3DDFA-V3
cp 3DDFA-V3/utils/cpu_renderer.py ./utils/
cp -r 3DDFA-V3/utils/cython_renderer ./utils/

pip install Cython

cd util/cython_renderer/
python setup.py build_ext -i
cd ../.. # ./Deep3DFaceRecon_pytorch
```
3. Skip this step for inference/test, but you need run test.py with "--renderer_type none --no_viz" options


3. Install Arcface Pytorch:
```
cd .. # ./Deep3DFaceRecon_pytorch
git clone https://github.com/deepinsight/insightface.git
cp -r ./insightface/recognition/arcface_torch ./models/
```
Expand Down Expand Up @@ -137,6 +152,24 @@ Deep3DFaceRecon_pytorch
```

### Test with custom images

#### Face detection
To detect 5 facial landmarks from test images, first we need install [InsightFace](https://github.com/deepinsight/insightface) library:
```
pip install insightface onnxruntime
```
or
```
pip install insightface onnxruntime-gpu
```

and then, run the following command:
```
python detect_faces_by_insightface.py <folder_to_test_images>
```

#### Face reconstruction

To reconstruct 3d faces from test images, organize the test image folder as follows:
```
Deep3DFaceRecon_pytorch
Expand All @@ -159,6 +192,37 @@ python test.py --name=<model_name> --epoch=20 --img_folder=<folder_to_test_image
# get reconstruction results of example images
python test.py --name=<model_name> --epoch=20 --img_folder=./datasets/examples
```

On **MacOS**, you can run the test script with CPU or Apple Silicon (M1, M2, M3 chips) by adding "--device cpu" or "--device mps" to the command. For example,

run with MPS:
```
# get reconstruction results of your custom images
python test.py --name=<model_name> --epoch=20 --img_folder=<folder_to_test_images> --device mps --renderer_type face3d

# no visualization
python test.py --name=<model_name> --epoch=20 --img_folder=<folder_to_test_images> --device mps --renderer_type none--no_viz

# get reconstruction results of example images
python test.py --name=<model_name> --epoch=20 --img_folder=./datasets/examples --device mps --renderer_type face3d

# no visualization
python test.py --name=<model_name> --epoch=20 --img_folder=./datasets/examples --device mps --renderer_type none --no_viz
```

or run with CPU:
```
# get reconstruction results of your custom images
python test.py --name=<model_name> --epoch=20 --img_folder=<folder_to_test_images> --device cpu --renderer_type face3d

python test.py --name=<model_name> --epoch=20 --img_folder=<folder_to_test_images> --device cpu --renderer_type none --no_viz

# get reconstruction results of example images
python test.py --name=<model_name> --epoch=20 --img_folder=./datasets/examples --device cpu --renderer_type face3d

python test.py --name=<model_name> --epoch=20 --img_folder=./datasets/examples --device cpu --renderer_type none --no_viz
```

**_Following [#108](https://github.com/sicxu/Deep3DFaceRecon_pytorch/issues/108), if you don't have OpenGL environment, you can simply add "--use_opengl False" to use CUDA context. Make sure you have updated the nvdiffrast to the latest version._**

Results will be saved into ./checkpoints/<model_name>/results/<folder_to_test_images>, which contain the following files:
Expand Down
75 changes: 75 additions & 0 deletions detect_faces_by_insightface.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# coding=utf-8
"""
Detect faces and landmarks in images using the InsightFace library.

Authors:
zhaoyafei (zhaoyafei0210@gmail.com, https://github.com/walkoncross)
"""

import os
import os.path as osp

import cv2
from insightface.app import FaceAnalysis


def detect_faces(input_dir):
# Initialize the face analysis app
app = FaceAnalysis(
allowed_modules=["detection", "alignment"],
providers=[
"CUDAExecutionProvider",
"CoreMLExecutionProvider",
"CPUExecutionProvider",
],
)
app.prepare(ctx_id=0, det_size=(640, 640))

# Create the output directory if it doesn't exist
output_dir = os.path.join(input_dir, "detections")
os.makedirs(output_dir, exist_ok=True)

# Iterate over all images in the input directory
file_list = [
ff
for ff in os.listdir(input_dir)
if osp.splitext(ff)[-1].lower() in [".png", ".jpg", ".jpeg", ".bmp"]
]

print(f"--> image files: \n{file_list}")

for ii, filename in enumerate(file_list):
print(f"--> {ii}: {filename}")
image_path = os.path.join(input_dir, filename)
img = cv2.imread(image_path)

# Detect faces in the image
faces = app.get(img)

if faces:
print(f"Detected {len(faces)} faces")
# Get the face with the highest score
best_face = max(faces, key=lambda face: face["det_score"])

# Get the 5 key points of the best face
keypoints = best_face["kps"]

# Write the key points to a txt file
output_path = os.path.join(
output_dir, f"{os.path.splitext(filename)[0]}.txt"
)
with open(output_path, "w") as f:
for point in keypoints:
f.write(f"{point[0]} {point[1]}\n")
else:
print(f"No faces detected")


if __name__ == "__main__":
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("input_dir", help="Directory containing images")
args = parser.parse_args()

detect_faces(args.input_dir)
1 change: 1 addition & 0 deletions models/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
arcface_torch/
7 changes: 4 additions & 3 deletions models/base_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,15 +152,16 @@ def eval(self):
net = getattr(self, name)
net.eval()

def test(self):
def test(self, do_render=True):
"""Forward function used in test time.

This function wraps <forward> function in no_grad() so we don't save intermediate steps for backprop
It also calls <compute_visuals> to produce additional visualization results
"""
with torch.no_grad():
self.forward()
self.compute_visuals()
self.forward(do_render=do_render)
if do_render:
self.compute_visuals()

def compute_visuals(self):
"""Calculate additional output images for visdom and HTML visualization"""
Expand Down
Loading