Update README.md
Browse files
README.md
CHANGED
@@ -5,122 +5,201 @@ language:
|
|
5 |
- en
|
6 |
pipeline_tag: image-to-image
|
7 |
---
|
|
|
8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
-
##
|
11 |
-
|
12 |
-
- Validation set: 21.70
|
13 |
|
14 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
```bash
|
18 |
-
git clone https://
|
|
|
19 |
```
|
|
|
|
|
20 |
```bash
|
21 |
-
|
22 |
-
git lfs pull
|
23 |
```
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
```python
|
26 |
from PIL import Image
|
27 |
import os
|
28 |
import numpy as np
|
29 |
import tensorflow as tf
|
30 |
import requests
|
31 |
-
from skimage.color import lab2rgb
|
32 |
import matplotlib.pyplot as plt
|
|
|
33 |
from models.auto_encoder_gray2color import SpatialAttention
|
34 |
```
|
35 |
-
|
|
|
|
|
|
|
36 |
```python
|
37 |
-
# Load the saved model once at startup
|
38 |
load_model_path = "./ckpts/best_model.h5"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
print(f"Loading model from {load_model_path}...")
|
41 |
loaded_autoencoder = tf.keras.models.load_model(
|
42 |
-
load_model_path,
|
43 |
-
custom_objects={'SpatialAttention': SpatialAttention}
|
44 |
)
|
|
|
45 |
```
|
46 |
|
47 |
-
### Define Functions
|
|
|
|
|
48 |
```python
|
49 |
def process_image(input_img):
|
50 |
-
|
|
|
51 |
original_width, original_height = input_img.size
|
|
|
|
|
|
|
|
|
|
|
52 |
|
53 |
-
#
|
54 |
-
|
55 |
-
img = img.resize((WIDTH, HEIGHT)) # Resize to 512x512 for model
|
56 |
-
img_array = tf.keras.preprocessing.image.img_to_array(img) / 255.0 # Normalize to [0, 1]
|
57 |
-
img_array = img_array[None, ..., 0:1] # Add batch dimension, shape: (1, 512, 512, 1)
|
58 |
-
|
59 |
-
# Run inference (assuming loaded_autoencoder predicts a*b* channels)
|
60 |
-
output_array = loaded_autoencoder.predict(img_array) # Shape: (1, 512, 512, 2) for a*b*
|
61 |
-
print("output_array shape: ", output_array.shape)
|
62 |
-
|
63 |
-
# Extract L* (grayscale input) and a*b* (model output)
|
64 |
-
L_channel = img_array[0, :, :, 0] * 100.0 # Denormalize L* to [0, 100]
|
65 |
-
ab_channels = output_array[0] * 128.0 # Denormalize a*b* to [-128, 128]
|
66 |
-
|
67 |
-
# Combine L*, a*, b* into a 3-channel L*a*b* image
|
68 |
-
lab_image = np.stack([L_channel, ab_channels[:, :, 0], ab_channels[:, :, 1]], axis=-1) # Shape: (512, 512, 3)
|
69 |
-
|
70 |
-
# Convert L*a*b* to RGB
|
71 |
-
rgb_array = lab2rgb(lab_image) # Convert to RGB, output in [0, 1]
|
72 |
-
rgb_array = np.clip(rgb_array, 0, 1) * 255.0 # Scale to [0, 255]
|
73 |
-
rgb_image = Image.fromarray(rgb_array.astype(np.uint8), mode="RGB") # Create RGB PIL image
|
74 |
-
|
75 |
-
# Resize output image to match input image resolution
|
76 |
-
rgb_image = rgb_image.resize((original_width, original_height), Image.Resampling.LANCZOS)
|
77 |
-
|
78 |
-
return rgb_image
|
79 |
-
|
80 |
-
def process_and_plot_images(input_path):
|
81 |
-
# Read input image
|
82 |
-
input_img = Image.open(input_path)
|
83 |
|
84 |
-
#
|
85 |
-
|
|
|
|
|
86 |
|
87 |
-
#
|
88 |
-
|
|
|
89 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
90 |
return input_img, output_img
|
91 |
|
92 |
-
def
|
93 |
-
|
94 |
-
plt.figure(figsize=(17, 8), dpi=300)
|
95 |
|
96 |
-
# Plot input image
|
97 |
plt.subplot(1, 2, 1)
|
98 |
-
plt.imshow(input_img, cmap=
|
99 |
-
plt.title("Input Image")
|
100 |
-
plt.axis(
|
101 |
|
102 |
-
# Plot output image
|
103 |
plt.subplot(1, 2, 2)
|
104 |
-
plt.imshow(output_img
|
105 |
-
plt.title("Output Image")
|
106 |
-
plt.axis(
|
107 |
|
108 |
-
# Save
|
109 |
-
plt.savefig("output.jpg", dpi=300, bbox_inches=
|
110 |
-
|
111 |
-
# Show the plot
|
112 |
plt.show()
|
113 |
```
|
114 |
-
|
|
|
|
|
|
|
115 |
```python
|
116 |
-
#
|
117 |
WIDTH, HEIGHT = 512, 512
|
118 |
-
|
119 |
-
image_path = "<input_image.jpg>"
|
120 |
-
input_img, output_img = process_and_plot_images(image_path)
|
121 |
|
122 |
-
|
|
|
|
|
123 |
```
|
124 |
|
125 |
-
### Example Output
|
126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
- en
|
6 |
pipeline_tag: image-to-image
|
7 |
---
|
8 |
+
# Autoencoder Grayscale2Color Landscape 🛡️
|
9 |
|
10 |
+
[](https://huggingface.co/docs/hub)
|
11 |
+
[](https://pypi.org/project/pillow/)
|
12 |
+
[](https://numpy.org/)
|
13 |
+
[](https://www.tensorflow.org/)
|
14 |
+
[](https://gradio.app/)
|
15 |
+
[](https://opensource.org/licenses/MIT)
|
16 |
|
17 |
+
## Introduction
|
18 |
+
Transform grayscale landscape images into vibrant, full-color visuals with this autoencoder model. Built from scratch, this project leverages deep learning to predict color channels (a*b* in L*a*b* color space) from grayscale inputs, delivering impressive results with a sleek, minimalist design. 🌄
|
|
|
19 |
|
20 |
+
## Key Features
|
21 |
+
- 📸 Converts grayscale landscape images to vivid RGB.
|
22 |
+
- 🧠 Custom autoencoder with spatial attention for enhanced detail.
|
23 |
+
- ⚡ Optimized for high-quality inference at 512x512 resolution.
|
24 |
+
- 📊 Achieves a PSNR of 21.70 on the validation set.
|
25 |
+
|
26 |
+
## Notebook
|
27 |
+
Explore the implementation in our Jupyter notebook:
|
28 |
+
[](https://colab.research.google.com/github/danhtran2mind/autoencoder-grayscale2color-landscape-from-scratch/blob/main/notebooks/autoencoder-grayscale-to-color-landscape.ipynb)
|
29 |
+
[](https://studiolab.sagemaker.aws/import/github/danhtran2mind/autoencoder-grayscale2color-landscape-from-scratch/blob/main/notebooks/autoencoder-grayscale-to-color-landscape.ipynb)
|
30 |
+
[](https://deepnote.com/launch?url=https://github.com/danhtran2mind/autoencoder-grayscale2color-landscape-from-scratch/blob/main/notebooks/autoencoder-grayscale-to-color-landscape.ipynb)
|
31 |
+
[](https://mybinder.org/v2/gh/danhtran2mind/autoencoder-grayscale2color-landscape-from-scratch/main?filepath=autoencoder-grayscale-to-color-landscape.ipynb)
|
32 |
+
[](https://github.com/danhtran2mind/autoencoder-grayscale2color-landscape-from-scratch/blob/main/notebooks/autoencoder-grayscale-to-color-landscape.ipynb)
|
33 |
+
|
34 |
+
## Dataset
|
35 |
+
Details about the dataset are available in the [README Dataset](./dataset/README.md). 📂
|
36 |
+
|
37 |
+
## From Scratch Model
|
38 |
+
Custom-built autoencoder with a spatial attention mechanism, trained **FROM SCRATCH** to predict a*b* color channels from grayscale (L*) inputs. 🧩
|
39 |
|
40 |
+
## Demonstration
|
41 |
+
Experience the brilliance of our cutting-edge technology! Transform grayscale landscapes into vibrant colors with our interactive demo.
|
42 |
+
|
43 |
+
[](https://huggingface.co/spaces/danhtran2mind/autoencoder-grayscale2color-landscape)
|
44 |
+
|
45 |
+

|
46 |
+
|
47 |
+
## Installation
|
48 |
+
|
49 |
+
### Step 1: Clone the Repository
|
50 |
```bash
|
51 |
+
git clone https://github.com/danhtran2mind/autoencoder-grayscale2color-landscape-from-scratch
|
52 |
+
cd /autoencoder-grayscale2color-landscape-from-scratch
|
53 |
```
|
54 |
+
|
55 |
+
### Step 2: Install Dependencies
|
56 |
```bash
|
57 |
+
pip install -r requirements.txt
|
|
|
58 |
```
|
59 |
+
|
60 |
+
## Usage
|
61 |
+
|
62 |
+
Follow these steps to colorize images programmatically using Python.
|
63 |
+
|
64 |
+
### 1. Import Required Libraries
|
65 |
+
Install and import the necessary libraries for image processing and model inference.
|
66 |
+
|
67 |
```python
|
68 |
from PIL import Image
|
69 |
import os
|
70 |
import numpy as np
|
71 |
import tensorflow as tf
|
72 |
import requests
|
|
|
73 |
import matplotlib.pyplot as plt
|
74 |
+
from skimage.color import lab2rgb
|
75 |
from models.auto_encoder_gray2color import SpatialAttention
|
76 |
```
|
77 |
+
|
78 |
+
### 2. Load the Pre-trained Model
|
79 |
+
Download and load the autoencoder model from a remote source if it’s not already available locally.
|
80 |
+
|
81 |
```python
|
|
|
82 |
load_model_path = "./ckpts/best_model.h5"
|
83 |
+
os.makedirs(os.path.dirname(load_model_path), exist_ok=True)
|
84 |
+
|
85 |
+
if not os.path.exists(load_model_path):
|
86 |
+
url = "https://huggingface.co/danhtran2mind/autoencoder-grayscale2color-landscape/resolve/main/ckpts/best_model.h5"
|
87 |
+
print(f"Downloading model from {url}...")
|
88 |
+
with requests.get(url, stream=True) as response:
|
89 |
+
response.raise_for_status()
|
90 |
+
with open(load_model_path, "wb") as f:
|
91 |
+
for chunk in response.iter_content(chunk_size=8192):
|
92 |
+
f.write(chunk)
|
93 |
+
print("Model downloaded successfully.")
|
94 |
|
95 |
print(f"Loading model from {load_model_path}...")
|
96 |
loaded_autoencoder = tf.keras.models.load_model(
|
97 |
+
load_model_path, custom_objects={"SpatialAttention": SpatialAttention}
|
|
|
98 |
)
|
99 |
+
print("Model loaded successfully.")
|
100 |
```
|
101 |
|
102 |
+
### 3. Define Image Processing Functions
|
103 |
+
These functions handle image preprocessing, colorization, and visualization.
|
104 |
+
|
105 |
```python
|
106 |
def process_image(input_img):
|
107 |
+
"""Convert a grayscale image to color using the autoencoder."""
|
108 |
+
# Store original dimensions
|
109 |
original_width, original_height = input_img.size
|
110 |
+
|
111 |
+
# Preprocess: Convert to grayscale, resize, and normalize
|
112 |
+
img = input_img.convert("L").resize((512, 512))
|
113 |
+
img_array = tf.keras.preprocessing.image.img_to_array(img) / 255.0
|
114 |
+
img_array = img_array[None, ..., 0:1] # Add batch dimension
|
115 |
|
116 |
+
# Predict color channels
|
117 |
+
output_array = loaded_autoencoder.predict(img_array)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
118 |
|
119 |
+
# Reconstruct LAB image
|
120 |
+
L_channel = img_array[0, :, :, 0] * 100.0 # Scale L channel
|
121 |
+
ab_channels = output_array[0] * 128.0 # Scale ab channels
|
122 |
+
lab_image = np.stack([L_channel, ab_channels[:, :, 0], ab_channels[:, :, 1]], axis=-1)
|
123 |
|
124 |
+
# Convert to RGB and clip values
|
125 |
+
rgb_array = lab2rgb(lab_image)
|
126 |
+
rgb_array = np.clip(rgb_array, 0, 1) * 255.0
|
127 |
|
128 |
+
# Create and resize output image
|
129 |
+
rgb_image = Image.fromarray(rgb_array.astype(np.uint8), mode="RGB")
|
130 |
+
return rgb_image.resize((original_width, original_height), Image.Resampling.LANCZOS)
|
131 |
+
|
132 |
+
def process_and_save_image(image_path):
|
133 |
+
"""Process an image and save the colorized result."""
|
134 |
+
input_img = Image.open(image_path)
|
135 |
+
output_img = process_image(input_img)
|
136 |
+
output_img.save("output.jpg")
|
137 |
return input_img, output_img
|
138 |
|
139 |
+
def plot_images(input_img, output_img):
|
140 |
+
"""Display input and output images side by side."""
|
141 |
+
plt.figure(figsize=(17, 8), dpi=300)
|
142 |
|
143 |
+
# Plot input grayscale image
|
144 |
plt.subplot(1, 2, 1)
|
145 |
+
plt.imshow(input_img, cmap="gray")
|
146 |
+
plt.title("Input Grayscale Image")
|
147 |
+
plt.axis("off")
|
148 |
|
149 |
+
# Plot output colorized image
|
150 |
plt.subplot(1, 2, 2)
|
151 |
+
plt.imshow(output_img)
|
152 |
+
plt.title("Colorized Output Image")
|
153 |
+
plt.axis("off")
|
154 |
|
155 |
+
# Save and display the plot
|
156 |
+
plt.savefig("output.jpg", dpi=300, bbox_inches="tight")
|
|
|
|
|
157 |
plt.show()
|
158 |
```
|
159 |
+
|
160 |
+
### 4. Perform Inference
|
161 |
+
Run the colorization process on a sample image.
|
162 |
+
|
163 |
```python
|
164 |
+
# Set image dimensions and path
|
165 |
WIDTH, HEIGHT = 512, 512
|
166 |
+
image_path = "<path_to_input_image.jpg>" # Replace with your image path
|
|
|
|
|
167 |
|
168 |
+
# Process and visualize the image
|
169 |
+
input_img, output_img = process_and_save_image(image_path)
|
170 |
+
plot_images(input_img, output_img)
|
171 |
```
|
172 |
|
173 |
+
### 5. Example Output
|
174 |
+
The output will be a side-by-side comparison of the input grayscale image and the colorized result, saved as `output.jpg`. For a sample result, see the example below:
|
175 |
+

|
176 |
+
|
177 |
+
## Training Hyperparameters
|
178 |
+
- **Resolution**: 512x512 pixels
|
179 |
+
- **Color Space**: L*a*b*
|
180 |
+
- **Custom Layer**: SpatialAttention
|
181 |
+
- **Model File**: `best_model.h5`
|
182 |
+
- **Epochs**: 100
|
183 |
+
|
184 |
+
## Callbacks
|
185 |
+
- **Early Stopping**: Monitors `val_loss`, patience of 20 epochs, restores best weights.
|
186 |
+
- **ReduceLROnPlateau**: Monitors `val_loss`, reduces learning rate by 50% after 5 epochs, minimum learning rate of 1e-6.
|
187 |
+
- **BackupAndRestore**: Saves checkpoints to `./ckpts/backup`.
|
188 |
+
-
|
189 |
+
## Metrics
|
190 |
+
- **PSNR (Validation)**: 21.70 📈
|
191 |
+
|
192 |
+
## Environment
|
193 |
+
- Python 3.11.11
|
194 |
+
- Libraies
|
195 |
+
```
|
196 |
+
numpy==1.26.4
|
197 |
+
tensorflow==2.18.0
|
198 |
+
opencv-python==4.11.0.86
|
199 |
+
scikit-image==0.25.2
|
200 |
+
matplotlib==3.7.2
|
201 |
+
scikit-image==0.25.2
|
202 |
+
```
|
203 |
+
|
204 |
+
## Contact
|
205 |
+
For questions or issues, reach out via the [GitHub Issues](https://github.com/danhtran2mind/autoencoder-grayscale2color-landscape-from-scratch/issues) tab. 🚀
|