GFPGAN: Real-world Face Restoration
GFPGAN (Generative Facial Prior-guided Face Restoration) is a Python library that provides practical algorithms for high-quality face restoration, especially for degraded real-world images. It leverages a pre-trained GAN (Generative Adversarial Network) as a facial prior for robust restoration. The current version is 1.3.8, with a history of frequent minor updates addressing bugs, adding features, and refining model architectures.
Common errors
-
ModuleNotFoundError: No module named 'gfpgan.archs.codeformer_arch'
cause This module was removed in GFPGAN v1.3.8, leading to a `ModuleNotFoundError` if your code attempts to import or use `codeformer_arch`.fixIf `codeformer` is essential, downgrade to GFPGAN v1.3.7 or earlier (`pip install gfpgan==1.3.7`). Otherwise, remove any code references to `codeformer` components. -
FileNotFoundError: [Errno 2] No such file or directory: 'GFPGANv1.3.pth'
cause The specified model file (e.g., 'GFPGANv1.3.pth') could not be found. GFPGAN models are not installed with the pip package.fixDownload the required `.pth` model file (e.g., GFPGANv1.3.pth) from the official GitHub releases (https://github.com/TencentARC/GFPGAN/releases) and ensure its path is correctly provided to the `GFPGANer` constructor. -
RuntimeError: CUDA error: invalid device ordinal
cause This typically indicates an issue with PyTorch's CUDA setup, such as attempting to use a GPU device that doesn't exist, is out of range, or CUDA drivers are not properly configured.fixVerify your PyTorch and CUDA installations. Ensure your `device` parameter in `GFPGANer` is set correctly (e.g., `device='cuda'` if a GPU is present, otherwise `device='cpu'`). Check `torch.cuda.is_available()` and `torch.cuda.device_count()`. -
ModuleNotFoundError: No module named 'basicsr'
cause `basicsr` is a core dependency for GFPGAN, and this error indicates it was not installed or is not accessible in the current environment.fixEnsure `basicsr` is installed: `pip install basicsr`. If you installed `gfpgan` via `pip`, `basicsr` should have been installed automatically; check your environment and Python path.
Warnings
- breaking The `codeformer` integration was removed in GFPGAN v1.3.8. If your code relied on this component, it will break or require modification.
- gotcha GFPGAN models (e.g., `GFPGANv1.3.pth`) are not bundled with the pip package and must be manually downloaded from the official GitHub releases page. The library will not function without a valid model path.
- gotcha GFPGAN relies on PyTorch and potentially CUDA for optimal performance. Incorrect PyTorch/CUDA installation or version mismatches can lead to runtime errors or force CPU-only processing.
- breaking An `ImportError` was present in v1.3.0 due to a missing file. While fixed in v1.3.1, this highlights potential instability in specific minor point releases.
Install
-
pip install gfpgan
Imports
- GFPGANer
from gfpgan import GFPGANer
Quickstart
import cv2
import numpy as np
import os
from gfpgan import GFPGANer
# 1. Prepare a dummy input image
# In a real scenario, you would load your image: img = cv2.imread('path/to/your/image.jpg', cv2.IMREAD_COLOR)
# For a runnable example, create a 256x256 black image with some noise.
input_img = np.zeros((256, 256, 3), dtype=np.uint8)
noise = np.random.randint(-50, 50, (256, 256, 3), dtype=np.int16)
input_img = np.clip(input_img + noise, 0, 255).astype(np.uint8)
# 2. Download the pre-trained GFPGAN model
# GFPGAN models are NOT bundled with the pip package and must be downloaded manually.
# Download GFPGANv1.3.pth from: https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth
model_path = 'GFPGANv1.3.pth' # Place the downloaded model in the same directory as your script
if not os.path.exists(model_path):
print(f"Warning: Model file '{model_path}' not found. Please download it from:")
print(" https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth")
print(" Proceeding with a placeholder; actual enhancement will not occur without the model.")
enhanced_img = input_img.copy() # Fallback for quickstart if model not present
else:
# 3. Initialize GFPGANer
# Use 'cpu' for broad compatibility. Change to 'cuda' if a GPU is available.
restorer = GFPGANer(
model_path=model_path,
upscale=2, # Upscale factor: 1, 2, or 4
arch='clean', # Model architecture: 'original' or 'clean'
channel_multiplier=2,
bg_upsampler=None, # Set to 'realesrgan' if you want background upsampling
device='cpu' # 'cuda' for GPU, 'cpu' for CPU
)
# 4. Enhance the image
# The enhance method returns cropped_faces, restored_faces, and the final enhanced_img.
cropped_faces, restored_faces, enhanced_img = restorer.enhance(
input_img, # Input image (BGR format)
has_aligned=False, # Set to True if input faces are already aligned
only_center_face=False, # Set to True to only enhance the most prominent face
paste_back=True # Set to True to paste restored faces back into the original image
)
# 5. Save the output image
output_path = 'gfpgan_enhanced_output.jpg'
cv2.imwrite(output_path, enhanced_img)
print(f"Enhanced image (or original if model was missing) saved to {output_path}")