Upload 19 files
Browse files- .gitattributes +12 -0
- LICENSE +11 -0
- README.md +121 -3
- inference.py +377 -0
- input/bw1.jpg +3 -0
- input/bw2.jpg +3 -0
- input/bw3.jpg +3 -0
- input/bw4.jpg +3 -0
- input/bw5.jpg +3 -0
- input/bw6.jpg +3 -0
- models/v6_generator.onnx +3 -0
- models/v6_sam_encoder.onnx +3 -0
- output/bw1.jpg +3 -0
- output/bw2.jpg +3 -0
- output/bw3.jpg +3 -0
- output/bw4.jpg +3 -0
- output/bw5.jpg +3 -0
- output/bw6.jpg +3 -0
- requirements-cuda.txt +5 -0
- requirements.txt +5 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,15 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
input/bw1.jpg filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
input/bw2.jpg filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
input/bw3.jpg filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
input/bw4.jpg filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
input/bw5.jpg filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
input/bw6.jpg filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
output/bw1.jpg filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
output/bw2.jpg filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
output/bw3.jpg filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
output/bw4.jpg filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
output/bw5.jpg filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
output/bw6.jpg filter=lfs diff=lfs merge=lfs -text
|
LICENSE
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Manga Light Colorizer — ONNX Inference
|
| 2 |
+
|
| 3 |
+
This project uses dual licensing:
|
| 4 |
+
|
| 5 |
+
1. Model Weights (v6_generator.onnx)
|
| 6 |
+
Licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0).
|
| 7 |
+
https://creativecommons.org/licenses/by-nc-sa/4.0/
|
| 8 |
+
|
| 9 |
+
2. Inference Code (inference_v6_no_wd14.py, requirements.txt, and all other files except .onnx models)
|
| 10 |
+
Licensed under GNU General Public License v3 (GPL-3.0).
|
| 11 |
+
https://www.gnu.org/licenses/gpl-3.0.html
|
README.md
CHANGED
|
@@ -1,3 +1,121 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Manga Light Colorizer — ONNX Inference (WD14 Disabled)
|
| 2 |
+
|
| 3 |
+
Standalone inference script for the Manga Light Colorizer model with WD14 semantic guidance disabled.
|
| 4 |
+
|
| 5 |
+
## Quick Start
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
# Install dependencies
|
| 9 |
+
pip install -r requirements.txt
|
| 10 |
+
|
| 11 |
+
# Single image
|
| 12 |
+
python inference.py --input input/bw1.jpg
|
| 13 |
+
|
| 14 |
+
# All images in a folder
|
| 15 |
+
python inference.py --input input/
|
| 16 |
+
|
| 17 |
+
# Custom output folder
|
| 18 |
+
python inference.py --input input/ --output_dir output/
|
| 19 |
+
|
| 20 |
+
# Custom inference resolution
|
| 21 |
+
python inference.py --input input/ --infer-size 1024
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
## Arguments
|
| 25 |
+
|
| 26 |
+
| Argument | Required | Default | Description |
|
| 27 |
+
|----------|----------|---------|-------------|
|
| 28 |
+
| `--input` | Yes | - | Input grayscale image or folder |
|
| 29 |
+
| `--onnx-model` | No | `models/v6_generator.onnx` | Generator ONNX model path |
|
| 30 |
+
| `--sam-onnx` | No | `models/v6_sam_encoder.onnx` | SAM 2.1 encoder ONNX path |
|
| 31 |
+
| `--output_dir` | No | `./output/` | Output folder for colorized images |
|
| 32 |
+
| `--infer-size` | No | `768` | Inference resolution (square) |
|
| 33 |
+
| `--ort-device` | No | `cpu` | ONNX Runtime device (`cpu` or `cuda`) |
|
| 34 |
+
|
| 35 |
+
## Model Information
|
| 36 |
+
|
| 37 |
+
- **Architecture**: FastViT-SA36 Encoder + DualSemanticSAM Guide + UNet V6 Decoder
|
| 38 |
+
- **Training Resolution**: 512×512 pixels
|
| 39 |
+
- **Current Inference Resolution**: 768×768 pixels (default)
|
| 40 |
+
- **Output**: Resized back to original input resolution
|
| 41 |
+
|
| 42 |
+
### Important: Resolution Notice
|
| 43 |
+
|
| 44 |
+
> The model was trained at **512×512 pixels**. Inference currently runs at **768×768 pixels** by default.
|
| 45 |
+
>
|
| 46 |
+
> **More the inference resolution differs from 512×512, the less faithful the colors will be.**
|
| 47 |
+
>
|
| 48 |
+
> For best results, use the training resolution:
|
| 49 |
+
> ```bash
|
| 50 |
+
> # Best color accuracy, but lower resolution — matches training resolution
|
| 51 |
+
> python inference.py --input input/ --infer-size 512
|
| 52 |
+
>
|
| 53 |
+
> # Default (good quality)
|
| 54 |
+
> python inference.py --input input/
|
| 55 |
+
>
|
| 56 |
+
> # Higher resolution (may reduce color accuracy)
|
| 57 |
+
> python inference.py --input input/ --infer-size 1024
|
| 58 |
+
> ```
|
| 59 |
+
|
| 60 |
+
## Pipeline
|
| 61 |
+
|
| 62 |
+
```
|
| 63 |
+
Input (grayscale) → Resize to infer-size → SAM 2.1 (zeros) → Generator ONNX → Resize to original
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
## Requirements
|
| 67 |
+
|
| 68 |
+
- Python 3.10+
|
| 69 |
+
- onnxruntime
|
| 70 |
+
- numpy
|
| 71 |
+
- opencv-python
|
| 72 |
+
|
| 73 |
+
See [`requirements.txt`](requirements.txt) for full list.
|
| 74 |
+
|
| 75 |
+
## Gallery
|
| 76 |
+
|
| 77 |
+
The following gallery uses the **same source images** as the [manga-colorization-v2](https://github.com/qweasdd/manga-colorization-v2) project to facilitate direct comparison between models.
|
| 78 |
+
|
| 79 |
+
Comparison between input (left) and colorized output (right):
|
| 80 |
+
|
| 81 |
+
| Input (BW) | Colorized Output |
|
| 82 |
+
|------------|------------------|
|
| 83 |
+
| <img src="figures/bw1.jpg" width="512"> | <img src="figures/bw1-colorized.jpg" width="512"> |
|
| 84 |
+
| <img src="figures/bw2.jpg" width="512"> | <img src="figures/bw2-colorized.jpg" width="512"> |
|
| 85 |
+
| <img src="figures/bw3.jpg" width="512"> | <img src="figures/bw3-colorized.jpg" width="512"> |
|
| 86 |
+
| <img src="figures/bw4.jpg" width="512"> | <img src="figures/bw4-colorized.jpg" width="512"> |
|
| 87 |
+
| <img src="figures/bw5.jpg" width="512"> | <img src="figures/bw5-colorized.jpg" width="512"> |
|
| 88 |
+
| <img src="figures/bw6.jpg" width="512"> | <img src="figures/bw6-colorized.jpg" width="512"> |
|
| 89 |
+
|
| 90 |
+
## License
|
| 91 |
+
|
| 92 |
+
### Model Weights
|
| 93 |
+
Licensed under **CC BY-NC-SA 4.0** (Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International).
|
| 94 |
+
|
| 95 |
+
[](https://creativecommons.org/licenses/by-nc-sa/4.0/)
|
| 96 |
+
|
| 97 |
+
You may:
|
| 98 |
+
- Share — copy and redistribute the material in any medium or format
|
| 99 |
+
- Adapt — remix, transform, and build upon the material
|
| 100 |
+
|
| 101 |
+
Under the following terms:
|
| 102 |
+
- **Attribution** — You must give appropriate credit
|
| 103 |
+
- **NonCommercial** — You may not use the material for commercial purposes
|
| 104 |
+
- **ShareAlike** — If you remix, transform, or build upon the material, you must distribute your contributions under the same license
|
| 105 |
+
|
| 106 |
+
See: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
| 107 |
+
|
| 108 |
+
### Inference Code
|
| 109 |
+
Licensed under **GNU General Public License v3** (GPL-3.0).
|
| 110 |
+
|
| 111 |
+
[](https://www.gnu.org/licenses/gpl-3.0.html)
|
| 112 |
+
|
| 113 |
+
You may use, modify, and distribute this code under the terms of the GPL-3.0 license.
|
| 114 |
+
|
| 115 |
+
See: https://www.gnu.org/licenses/gpl-3.0.html
|
| 116 |
+
|
| 117 |
+
## Credits
|
| 118 |
+
|
| 119 |
+
Based on the Manga Light Colorizer project by Hugues.
|
| 120 |
+
|
| 121 |
+
Original project: https://github.com/your-username/manga-light-colorizer
|
inference.py
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Manga Light Colorizer - V6 ONNX Inference Script
|
| 4 |
+
|
| 5 |
+
No PyTorch — only ONNX runtime + numpy + cv2.
|
| 6 |
+
All semantic inputs are zeros (no semantic guidance).
|
| 7 |
+
|
| 8 |
+
Models auto-detected from models/ folder (relative to script location):
|
| 9 |
+
standalone/models/v6_generator.onnx
|
| 10 |
+
standalone/models/v6_sam_encoder.onnx
|
| 11 |
+
|
| 12 |
+
Usage:
|
| 13 |
+
python standalone/inference.py --input input.png
|
| 14 |
+
python standalone/inference.py --input input.png --infer-size 1024
|
| 15 |
+
python standalone/inference.py --input ./input_folder/
|
| 16 |
+
python standalone/inference.py --input input.png --output_dir ./output/
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import glob
|
| 21 |
+
import sys
|
| 22 |
+
import time
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
import cv2
|
| 26 |
+
import numpy as np
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
import onnxruntime as ort
|
| 30 |
+
except ImportError:
|
| 31 |
+
print("Error: onnxruntime not installed. Install with: pip install onnxruntime")
|
| 32 |
+
sys.exit(1)
|
| 33 |
+
|
| 34 |
+
# Supported image extensions
|
| 35 |
+
IMAGE_EXTENSIONS = {'*.jpg', '*.jpeg', '*.png', '*.bmp', '*.tiff', '*.tif', '*.webp'}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# ============================================================================
|
| 39 |
+
# STABLE UTILS (minimal, no external dependencies)
|
| 40 |
+
# ============================================================================
|
| 41 |
+
|
| 42 |
+
def denormalize_rgb(rgb_norm: np.ndarray) -> np.ndarray:
|
| 43 |
+
"""[-1, 1] -> [0, 255] uint8."""
|
| 44 |
+
return np.clip((rgb_norm + 1.0) * 127.5, 0, 255).astype(np.uint8)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def load_image(image_path: str, target_size: int = None, pad_to_multiple: int = 32):
|
| 48 |
+
"""
|
| 49 |
+
Load and preprocess grayscale image.
|
| 50 |
+
|
| 51 |
+
If target_size is specified, resize to that square size.
|
| 52 |
+
Otherwise, pad to nearest multiple of pad_to_multiple (preserves original resolution).
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
(processed_img, original_size, padding)
|
| 56 |
+
- original_size: (orig_W, orig_H)
|
| 57 |
+
- padding: (pad_bottom, pad_right) applied
|
| 58 |
+
"""
|
| 59 |
+
img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
|
| 60 |
+
if img is None:
|
| 61 |
+
raise ValueError(f"Failed to load image: {image_path}")
|
| 62 |
+
|
| 63 |
+
original_size = (img.shape[1], img.shape[0]) # (W, H)
|
| 64 |
+
|
| 65 |
+
if target_size is not None:
|
| 66 |
+
# Resize to fixed square size
|
| 67 |
+
img = cv2.resize(img, (target_size, target_size), interpolation=cv2.INTER_AREA)
|
| 68 |
+
return img, original_size, (0, 0)
|
| 69 |
+
|
| 70 |
+
# Pad to multiple of pad_to_multiple (required by 5-level encoder)
|
| 71 |
+
H, W = img.shape
|
| 72 |
+
pad_h = (pad_to_multiple - H % pad_to_multiple) % pad_to_multiple
|
| 73 |
+
pad_w = (pad_to_multiple - W % pad_to_multiple) % pad_to_multiple
|
| 74 |
+
|
| 75 |
+
if pad_h > 0 or pad_w > 0:
|
| 76 |
+
img = np.pad(img, ((0, pad_h), (0, pad_w)), mode='reflect')
|
| 77 |
+
|
| 78 |
+
return img, original_size, (pad_h, pad_w)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def extract_sam_features_onnx(
|
| 82 |
+
sam_session: ort.InferenceSession,
|
| 83 |
+
L_bw_norm: np.ndarray,
|
| 84 |
+
):
|
| 85 |
+
"""
|
| 86 |
+
Extract SAM features via ONNX. WD14 is intentionally DISABLED (zeros).
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
sam_session: ONNX Runtime session for SAM encoder
|
| 90 |
+
L_bw_norm: (H, W) grayscale in [-1, 1]
|
| 91 |
+
|
| 92 |
+
Returns:
|
| 93 |
+
sam_level0, sam_level1, wd14_embedding (all numpy)
|
| 94 |
+
"""
|
| 95 |
+
H, W = L_bw_norm.shape
|
| 96 |
+
|
| 97 |
+
# SAM: expects (B, 3, 1024, 1024) RGB in [0, 1]
|
| 98 |
+
L_01 = (L_bw_norm + 1.0) / 2.0 # [-1,1] -> [0,1]
|
| 99 |
+
# Resize to 1024x1024 for SAM
|
| 100 |
+
L_1024 = cv2.resize(L_01, (1024, 1024), interpolation=cv2.INTER_LINEAR)
|
| 101 |
+
rgb_sam = np.stack([L_1024, L_1024, L_1024], axis=0)[np.newaxis] # (1, 3, 1024, 1024)
|
| 102 |
+
rgb_sam = rgb_sam.astype(np.float32)
|
| 103 |
+
|
| 104 |
+
sam_out = sam_session.run(None, {'rgb_input': rgb_sam})
|
| 105 |
+
sam_level0 = sam_out[0] # (1, 256, 64, 64)
|
| 106 |
+
sam_level1 = sam_out[1] # (1, 256, 32, 32)
|
| 107 |
+
|
| 108 |
+
# WD14: DISABLED - return zeros
|
| 109 |
+
wd14_embedding = np.zeros((1, 1024), dtype=np.float32)
|
| 110 |
+
|
| 111 |
+
return sam_level0, sam_level1, wd14_embedding
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def colorize_onnx(
|
| 115 |
+
session: ort.InferenceSession,
|
| 116 |
+
L_bw: np.ndarray,
|
| 117 |
+
sam_level0: np.ndarray,
|
| 118 |
+
sam_level1: np.ndarray,
|
| 119 |
+
wd14_embedding: np.ndarray
|
| 120 |
+
) -> np.ndarray:
|
| 121 |
+
"""
|
| 122 |
+
Run ONNX inference.
|
| 123 |
+
|
| 124 |
+
Args:
|
| 125 |
+
session: ONNX Runtime session
|
| 126 |
+
L_bw: (H, W) grayscale in [0, 255]
|
| 127 |
+
sam_level0: (1, 256, Hs0, Ws0) float32
|
| 128 |
+
sam_level1: (1, 256, Hs1, Ws1) float32
|
| 129 |
+
wd14_embedding: (1, 1024) float32 (zeros - WD14 disabled)
|
| 130 |
+
|
| 131 |
+
Returns:
|
| 132 |
+
RGB output (H, W, 3) in [0, 255]
|
| 133 |
+
"""
|
| 134 |
+
# Normalize L_bw to [-1, 1]
|
| 135 |
+
L_norm = (L_bw.astype(np.float32) / 127.5) - 1.0
|
| 136 |
+
L_tensor = L_norm[np.newaxis, np.newaxis, :, :] # (1, 1, H, W)
|
| 137 |
+
|
| 138 |
+
# Run ONNX
|
| 139 |
+
ort_inputs = {
|
| 140 |
+
'L_bw': L_tensor,
|
| 141 |
+
'sam_level0': sam_level0,
|
| 142 |
+
'sam_level1': sam_level1,
|
| 143 |
+
'wd14_embedding': wd14_embedding,
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
rgb_pred = session.run(None, ort_inputs)[0] # (1, 3, H, W)
|
| 147 |
+
|
| 148 |
+
# Convert to (H, W, 3) uint8
|
| 149 |
+
rgb_pred = rgb_pred[0].transpose(1, 2, 0) # (H, W, 3)
|
| 150 |
+
rgb_output = denormalize_rgb(rgb_pred)
|
| 151 |
+
|
| 152 |
+
return rgb_output
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def get_output_path(input_path: Path, output_folder: Path, input_name: str) -> Path:
|
| 156 |
+
"""Generate output path from input path, preserving filename in output folder."""
|
| 157 |
+
return output_folder / input_name
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def collect_input_files(input_path: str) -> list:
|
| 161 |
+
"""Collect all image files from input (file or folder). Returns list of Path objects."""
|
| 162 |
+
input_p = Path(input_path)
|
| 163 |
+
files = []
|
| 164 |
+
|
| 165 |
+
if input_p.is_file():
|
| 166 |
+
files.append(input_p)
|
| 167 |
+
elif input_p.is_dir():
|
| 168 |
+
for ext in IMAGE_EXTENSIONS:
|
| 169 |
+
files.extend(Path(f) for f in glob.glob(str(input_p / ext), recursive=True))
|
| 170 |
+
# Sort for deterministic ordering
|
| 171 |
+
files.sort()
|
| 172 |
+
else:
|
| 173 |
+
raise ValueError(f"Input not found: {input_path}")
|
| 174 |
+
|
| 175 |
+
return files
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def process_image(
|
| 179 |
+
image_path: Path,
|
| 180 |
+
session: ort.InferenceSession,
|
| 181 |
+
sam_session: ort.InferenceSession,
|
| 182 |
+
output_folder: Path,
|
| 183 |
+
has_sam: bool,
|
| 184 |
+
infer_size: int = 512,
|
| 185 |
+
ort_device: str = 'cpu'
|
| 186 |
+
) -> tuple:
|
| 187 |
+
"""
|
| 188 |
+
Process a single image.
|
| 189 |
+
|
| 190 |
+
Args:
|
| 191 |
+
infer_size: Resolution to run inference at (square). Input is ALWAYS resized to this.
|
| 192 |
+
Output is ALWAYS resized back to original input resolution.
|
| 193 |
+
|
| 194 |
+
Returns:
|
| 195 |
+
(output_path, time_taken, success)
|
| 196 |
+
"""
|
| 197 |
+
t_start = time.time()
|
| 198 |
+
|
| 199 |
+
# Load original image (preserve original size before any transformation)
|
| 200 |
+
img_original = cv2.imread(str(image_path), cv2.IMREAD_GRAYSCALE)
|
| 201 |
+
if img_original is None:
|
| 202 |
+
raise ValueError(f"Failed to load image: {image_path}")
|
| 203 |
+
orig_W, orig_H = img_original.shape[1], img_original.shape[0]
|
| 204 |
+
|
| 205 |
+
# ALWAYS resize input to infer_size for inference
|
| 206 |
+
L_bw = cv2.resize(img_original, (infer_size, infer_size), interpolation=cv2.INTER_AREA)
|
| 207 |
+
|
| 208 |
+
H_in, W_in = L_bw.shape
|
| 209 |
+
|
| 210 |
+
# Extract features
|
| 211 |
+
L_norm = (L_bw.astype(np.float32) / 127.5) - 1.0 # [-1, 1]
|
| 212 |
+
|
| 213 |
+
if has_sam and sam_session is not None:
|
| 214 |
+
sam_level0, sam_level1, wd14_embedding = extract_sam_features_onnx(sam_session, L_norm)
|
| 215 |
+
else:
|
| 216 |
+
sam_level0 = np.zeros((1, 256, H_in // 16, W_in // 16), dtype=np.float32)
|
| 217 |
+
sam_level1 = np.zeros((1, 256, H_in // 32, W_in // 32), dtype=np.float32)
|
| 218 |
+
wd14_embedding = np.zeros((1, 1024), dtype=np.float32)
|
| 219 |
+
|
| 220 |
+
# Colorize
|
| 221 |
+
rgb_output = colorize_onnx(session, L_bw, sam_level0, sam_level1, wd14_embedding)
|
| 222 |
+
# rgb_output is now (infer_size, infer_size, 3)
|
| 223 |
+
|
| 224 |
+
# ALWAYS resize back to original input resolution
|
| 225 |
+
rgb_output = cv2.resize(rgb_output, (orig_W, orig_H), interpolation=cv2.INTER_LANCZOS4)
|
| 226 |
+
|
| 227 |
+
# Save output
|
| 228 |
+
output_path = get_output_path(image_path, output_folder, image_path.name)
|
| 229 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 230 |
+
cv2.imwrite(str(output_path), cv2.cvtColor(rgb_output, cv2.COLOR_RGB2BGR))
|
| 231 |
+
|
| 232 |
+
t_end = time.time()
|
| 233 |
+
return output_path, t_end - t_start, True
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
# ============================================================================
|
| 237 |
+
# MAIN
|
| 238 |
+
# ============================================================================
|
| 239 |
+
|
| 240 |
+
def main():
|
| 241 |
+
parser = argparse.ArgumentParser(
|
| 242 |
+
description='Manga Light Colorizer - V6 ONNX Inference',
|
| 243 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 244 |
+
epilog="""
|
| 245 |
+
Examples:
|
| 246 |
+
# Single file
|
| 247 |
+
python inference.py input.png --onnx-model v6_generator.onnx
|
| 248 |
+
|
| 249 |
+
# Folder (all images)
|
| 250 |
+
python inference.py ./input_folder/ --onnx-model v6_generator.onnx
|
| 251 |
+
|
| 252 |
+
# With SAM
|
| 253 |
+
python inference.py input.png --onnx-model v6_generator.onnx --sam-onnx v6_sam_encoder.onnx
|
| 254 |
+
|
| 255 |
+
# Custom output folder
|
| 256 |
+
python inference.py input.png --onnx-model v6_generator.onnx --output ./output_folder/
|
| 257 |
+
"""
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
parser.add_argument('--input', type=str, required=True,
|
| 261 |
+
help='Input grayscale image or folder of images')
|
| 262 |
+
parser.add_argument('--onnx-model', type=str, default=None,
|
| 263 |
+
help='Path to ONNX model (default: models/v6_generator.onnx relative to script)')
|
| 264 |
+
parser.add_argument('--sam-onnx', type=str, default=None,
|
| 265 |
+
help='SAM ONNX model path (default: models/v6_sam_encoder.onnx relative to script)')
|
| 266 |
+
parser.add_argument('--output_dir', type=str, default='./output/',
|
| 267 |
+
help='Output folder (default: ./output/)')
|
| 268 |
+
parser.add_argument('--infer-size', type=int, default=768,
|
| 269 |
+
help='Inference resolution (square). Default: 768. Input is resized to this for inference, output is resized back to original.')
|
| 270 |
+
parser.add_argument('--ort-device', type=str, default='cpu',
|
| 271 |
+
choices=['cpu', 'cuda'],
|
| 272 |
+
help='ONNX Runtime device (default: cpu)')
|
| 273 |
+
|
| 274 |
+
args = parser.parse_args()
|
| 275 |
+
|
| 276 |
+
# Auto-detect models from models/ folder (relative to script location)
|
| 277 |
+
script_dir = Path(__file__).resolve().parent
|
| 278 |
+
if args.onnx_model is None:
|
| 279 |
+
args.onnx_model = str(script_dir / 'models' / 'v6_generator.onnx')
|
| 280 |
+
if args.sam_onnx is None:
|
| 281 |
+
args.sam_onnx = str(script_dir / 'models' / 'v6_sam_encoder.onnx')
|
| 282 |
+
|
| 283 |
+
# Validate inputs
|
| 284 |
+
if not Path(args.input).exists():
|
| 285 |
+
print(f"Error: Input not found: {args.input}")
|
| 286 |
+
sys.exit(1)
|
| 287 |
+
if not Path(args.onnx_model).exists():
|
| 288 |
+
print(f"Error: ONNX model not found: {args.onnx_model}")
|
| 289 |
+
sys.exit(1)
|
| 290 |
+
|
| 291 |
+
# Setup output folder
|
| 292 |
+
output_folder = Path(args.output_dir)
|
| 293 |
+
output_folder.mkdir(parents=True, exist_ok=True)
|
| 294 |
+
|
| 295 |
+
# Detect SAM availability
|
| 296 |
+
has_sam = Path(args.sam_onnx).exists()
|
| 297 |
+
|
| 298 |
+
print("=" * 60)
|
| 299 |
+
|
| 300 |
+
# 1. Detect model paths
|
| 301 |
+
print(f"[1/4] Detected models:")
|
| 302 |
+
print(f" Generator: {args.onnx_model}")
|
| 303 |
+
if has_sam:
|
| 304 |
+
print(f" SAM: {args.sam_onnx}")
|
| 305 |
+
else:
|
| 306 |
+
print(f" SAM: (disabled)")
|
| 307 |
+
|
| 308 |
+
# 2. Load ONNX model
|
| 309 |
+
print(f"[2/4] Loading generator: {args.onnx_model}")
|
| 310 |
+
providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if args.ort_device == 'cuda' else ['CPUExecutionProvider']
|
| 311 |
+
session = ort.InferenceSession(args.onnx_model, providers=providers)
|
| 312 |
+
active_provider = session.get_providers()[0]
|
| 313 |
+
print(f" OK Provider: {active_provider}")
|
| 314 |
+
|
| 315 |
+
# 3. Load SAM (if provided)
|
| 316 |
+
sam_session = None
|
| 317 |
+
if has_sam:
|
| 318 |
+
print(f"[3/4] Loading SAM ONNX: {args.sam_onnx}")
|
| 319 |
+
sam_session = ort.InferenceSession(args.sam_onnx, providers=providers)
|
| 320 |
+
print(f" OK SAM loaded")
|
| 321 |
+
else:
|
| 322 |
+
print(f"[3/4] SAM: DISABLED (using zeros)")
|
| 323 |
+
|
| 324 |
+
# 4. Collect input files
|
| 325 |
+
print(f"[4/4] Processing images...")
|
| 326 |
+
try:
|
| 327 |
+
input_files = collect_input_files(args.input)
|
| 328 |
+
except ValueError as e:
|
| 329 |
+
print(f"Error: {e}")
|
| 330 |
+
sys.exit(1)
|
| 331 |
+
|
| 332 |
+
if not input_files:
|
| 333 |
+
print(f"Error: No image files found in: {args.input}")
|
| 334 |
+
sys.exit(1)
|
| 335 |
+
|
| 336 |
+
print(f" Found {len(input_files)} image(s)")
|
| 337 |
+
print(f" Output folder: {output_folder.resolve()}")
|
| 338 |
+
print()
|
| 339 |
+
|
| 340 |
+
# Process all images
|
| 341 |
+
total_time = 0
|
| 342 |
+
success_count = 0
|
| 343 |
+
fail_count = 0
|
| 344 |
+
|
| 345 |
+
print(f" Inference size: {args.infer_size}x{args.infer_size} (output resized to original)")
|
| 346 |
+
print()
|
| 347 |
+
|
| 348 |
+
for i, img_path in enumerate(input_files, 1):
|
| 349 |
+
print(f"[{i}/{len(input_files)}] Processing: {img_path.name}")
|
| 350 |
+
try:
|
| 351 |
+
out_path, elapsed, ok = process_image(
|
| 352 |
+
img_path, session, sam_session, output_folder, has_sam,
|
| 353 |
+
infer_size=args.infer_size,
|
| 354 |
+
ort_device=args.ort_device
|
| 355 |
+
)
|
| 356 |
+
if ok:
|
| 357 |
+
print(f" OK -> {out_path} ({elapsed:.2f}s)")
|
| 358 |
+
success_count += 1
|
| 359 |
+
else:
|
| 360 |
+
print(f" FAILED")
|
| 361 |
+
fail_count += 1
|
| 362 |
+
except Exception as e:
|
| 363 |
+
print(f" Error: {e}")
|
| 364 |
+
fail_count += 1
|
| 365 |
+
total_time += elapsed
|
| 366 |
+
|
| 367 |
+
# Summary
|
| 368 |
+
print()
|
| 369 |
+
print(f"{'=' * 60}")
|
| 370 |
+
print(f"Summary: {success_count}/{len(input_files)} succeeded, {fail_count} failed")
|
| 371 |
+
print(f"Total time: {total_time:.2f}s")
|
| 372 |
+
print(f"Output folder: {output_folder.resolve()}")
|
| 373 |
+
print(f"{'=' * 60}")
|
| 374 |
+
|
| 375 |
+
if __name__ == '__main__':
|
| 376 |
+
main()
|
| 377 |
+
|
input/bw1.jpg
ADDED
|
Git LFS Details
|
input/bw2.jpg
ADDED
|
Git LFS Details
|
input/bw3.jpg
ADDED
|
Git LFS Details
|
input/bw4.jpg
ADDED
|
Git LFS Details
|
input/bw5.jpg
ADDED
|
Git LFS Details
|
input/bw6.jpg
ADDED
|
Git LFS Details
|
models/v6_generator.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:48284fcf0b7a606270702630f559af88eecf95bc6cdec1ff8bce8663d12b4bb6
|
| 3 |
+
size 191335312
|
models/v6_sam_encoder.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:97c4cad5814e1fb12c13d1b23d3969dd9e2fce92d818539fe7db575140333a34
|
| 3 |
+
size 108983556
|
output/bw1.jpg
ADDED
|
Git LFS Details
|
output/bw2.jpg
ADDED
|
Git LFS Details
|
output/bw3.jpg
ADDED
|
Git LFS Details
|
output/bw4.jpg
ADDED
|
Git LFS Details
|
output/bw5.jpg
ADDED
|
Git LFS Details
|
output/bw6.jpg
ADDED
|
Git LFS Details
|
requirements-cuda.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Standalone dependencies for manga-light-colorizer inference scripts
|
| 2 |
+
# Only these libraries are required — no PyTorch, no src/ imports
|
| 3 |
+
onnxruntime-cuda>=1.16.0
|
| 4 |
+
numpy>=1.24.0
|
| 5 |
+
opencv-python>=4.8.0
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Standalone dependencies for manga-light-colorizer inference scripts
|
| 2 |
+
# Only these libraries are required — no PyTorch, no src/ imports
|
| 3 |
+
onnxruntime>=1.16.0
|
| 4 |
+
numpy>=1.24.0
|
| 5 |
+
opencv-python>=4.8.0
|