Upload folder using huggingface_hub
Browse files- dataset_scripts/README.md +63 -0
- dataset_scripts/__init__.py +0 -0
- dataset_scripts/caption_control_dataset.py +59 -0
- dataset_scripts/coco/coco_dataset.py +18 -0
- dataset_scripts/coco/preprocess.py +176 -0
- dataset_scripts/dci/dci_dataset.py +16 -0
- dataset_scripts/dci/preprocess.py +172 -0
- dataset_scripts/mjhq/mjhq_dataset.py +18 -0
- dataset_scripts/mjhq/preprocess.py +195 -0
- dataset_scripts/processor.py +168 -0
dataset_scripts/README.md
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ControlNet Dataset Preprocessing Tool
|
| 2 |
+
|
| 3 |
+
This script processes a dataset (e.g. COCO-Caption2017) to generate ControlNet-compatible training data, such as Canny edge maps or depth maps.
|
| 4 |
+
|
| 5 |
+
## Usage
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
python -m {dataset_name}.preprocess [OPTIONS]
|
| 9 |
+
```
|
| 10 |
+
|
| 11 |
+
For example:
|
| 12 |
+
|
| 13 |
+
```bash
|
| 14 |
+
python -m coco.preprocess \
|
| 15 |
+
--output_dir ./controlnet_data \
|
| 16 |
+
--cn_type canny \
|
| 17 |
+
--sample_size 10000 \
|
| 18 |
+
--enable_blur \
|
| 19 |
+
--dataset COCO-Caption2017 \
|
| 20 |
+
--split val
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
## Command Line Arguments
|
| 24 |
+
|
| 25 |
+
| Argument | Type | Default | Description |
|
| 26 |
+
|----------|------|---------|-------------|
|
| 27 |
+
| `--output_dir` | `str` | `../dataset/controlnet_datasets` | Directory where the processed data will be saved. |
|
| 28 |
+
| `--cn_type` | `str` | `canny` | Type of control map to generate. Options: `canny`, `depth`. |
|
| 29 |
+
| `--sample_size` | `int` | `5000` | Maximum number of samples to process. |
|
| 30 |
+
| `--enable_blur` | flag | `False` | Enable Gaussian blur preprocessing for Canny edge detection. |
|
| 31 |
+
| `--blur_kernel_size` | `int` | `3` | Kernel size used for Gaussian blur (must be odd). |
|
| 32 |
+
| `--dataset` | `str` | `COCO-Caption2017` | Name of the dataset to use. |
|
| 33 |
+
| `--split` | `str` | `val` | Dataset split to process (`train`, `val`, etc.). |
|
| 34 |
+
| `--enable_no_prompt` | flag | `False` | If set, removes prompts from the output. |
|
| 35 |
+
| `--random_sample` | flag | `False` | If set, randomly samples from the dataset instead of sequential order. |
|
| 36 |
+
|
| 37 |
+
## Notes
|
| 38 |
+
|
| 39 |
+
- **Canny mode** uses OpenCV edge detection; enabling `--enable_blur` can improve edge clarity.
|
| 40 |
+
- This tool is often used to generate paired image/control map datasets for ControlNet training or finetuning.
|
| 41 |
+
|
| 42 |
+
## Dependencies
|
| 43 |
+
|
| 44 |
+
Make sure to install any required packages before running the script:
|
| 45 |
+
|
| 46 |
+
```bash
|
| 47 |
+
pip install opencv-python tqdm
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
## Output Structure
|
| 51 |
+
|
| 52 |
+
The script will generate a directory with the following structure:
|
| 53 |
+
|
| 54 |
+
```
|
| 55 |
+
output_dir/
|
| 56 |
+
├── images/
|
| 57 |
+
│ ├── 000001.jpg
|
| 58 |
+
│ └── ...
|
| 59 |
+
├── controls/
|
| 60 |
+
│ ├── 000001.png # e.g., Canny edge or depth map
|
| 61 |
+
│ └── ...
|
| 62 |
+
└── meta.json # Optional metadata
|
| 63 |
+
```
|
dataset_scripts/__init__.py
ADDED
|
File without changes
|
dataset_scripts/caption_control_dataset.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import OrderedDict
|
| 2 |
+
import os
|
| 3 |
+
import json
|
| 4 |
+
import torch
|
| 5 |
+
from torch.utils.data import Dataset
|
| 6 |
+
from backend.torch.utils import load_image
|
| 7 |
+
|
| 8 |
+
class LimitedCache:
|
| 9 |
+
def __init__(self, max_size):
|
| 10 |
+
self.cache = OrderedDict()
|
| 11 |
+
self.max_size = max_size
|
| 12 |
+
|
| 13 |
+
def get(self, key, loader_fn):
|
| 14 |
+
if key in self.cache:
|
| 15 |
+
self.cache.move_to_end(key)
|
| 16 |
+
return self.cache[key]
|
| 17 |
+
else:
|
| 18 |
+
value = loader_fn(key)
|
| 19 |
+
self.cache[key] = value
|
| 20 |
+
if len(self.cache) > self.max_size:
|
| 21 |
+
self.cache.popitem(last=False)
|
| 22 |
+
return value
|
| 23 |
+
|
| 24 |
+
class CaptionControlDataset(Dataset):
|
| 25 |
+
@staticmethod
|
| 26 |
+
def collate_fn(batch):
|
| 27 |
+
return [(prompt, image, control) for prompt, image, control in batch]
|
| 28 |
+
|
| 29 |
+
def __init__(self, path, cache_size=1024):
|
| 30 |
+
super().__init__()
|
| 31 |
+
self.base_path = path
|
| 32 |
+
with open(os.path.join(path, "metadata.json"), "r") as f:
|
| 33 |
+
self.metadata = json.load(f)
|
| 34 |
+
|
| 35 |
+
self.image_cache = LimitedCache(cache_size)
|
| 36 |
+
self.control_cache = LimitedCache(cache_size)
|
| 37 |
+
|
| 38 |
+
def __len__(self):
|
| 39 |
+
return len(self.metadata)
|
| 40 |
+
|
| 41 |
+
def __getitem__(self, idx):
|
| 42 |
+
item = self.metadata[idx]
|
| 43 |
+
prompt = item["prompt"]
|
| 44 |
+
image_path = os.path.join(self.base_path, item["image"])
|
| 45 |
+
control_path = os.path.join(self.base_path, item["control"])
|
| 46 |
+
|
| 47 |
+
image = self.image_cache.get(image_path, load_image)
|
| 48 |
+
control = self.control_cache.get(control_path, load_image)
|
| 49 |
+
|
| 50 |
+
return prompt, image, control
|
| 51 |
+
|
| 52 |
+
def get_dataloader(self, batch_size=1, shuffle=False, **kwargs):
|
| 53 |
+
return torch.utils.data.DataLoader(
|
| 54 |
+
self,
|
| 55 |
+
batch_size=batch_size,
|
| 56 |
+
shuffle=shuffle,
|
| 57 |
+
collate_fn=self.collate_fn,
|
| 58 |
+
**kwargs,
|
| 59 |
+
)
|
dataset_scripts/coco/coco_dataset.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataset.caption_control_dataset import CaptionControlDataset
|
| 2 |
+
|
| 3 |
+
COCODataset = CaptionControlDataset
|
| 4 |
+
|
| 5 |
+
if __name__ == "__main__":
|
| 6 |
+
dataset = COCODataset(
|
| 7 |
+
path="../dataset/controlnet_datasets/COCO-Caption2017-canny", cache_size=16
|
| 8 |
+
)
|
| 9 |
+
data_loader = dataset.get_dataloader(batch_size=1)
|
| 10 |
+
|
| 11 |
+
for i, batch in enumerate(data_loader):
|
| 12 |
+
prompt, image, control = batch[0]
|
| 13 |
+
print("prompt:", prompt)
|
| 14 |
+
print("image:", image)
|
| 15 |
+
print("control:", control)
|
| 16 |
+
print("--------------")
|
| 17 |
+
if i > 10:
|
| 18 |
+
break
|
dataset_scripts/coco/preprocess.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
import os
|
| 3 |
+
import random
|
| 4 |
+
from tqdm import tqdm # To measure processing time
|
| 5 |
+
from dataset.processor import ControlNetPreprocessor
|
| 6 |
+
from datasets import load_dataset
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def create_dataset(
|
| 10 |
+
preprocessor,
|
| 11 |
+
dataset,
|
| 12 |
+
output_dir,
|
| 13 |
+
enable_no_prompt=False,
|
| 14 |
+
):
|
| 15 |
+
"""
|
| 16 |
+
Creates a ControlNet dataset by processing images from a source dataset.
|
| 17 |
+
|
| 18 |
+
Args:
|
| 19 |
+
preprocessor: The ControlNetPreprocessor instance
|
| 20 |
+
dataset: The source dataset (e.g., COCO)
|
| 21 |
+
output_dir: Directory to save the processed dataset
|
| 22 |
+
cn_type: Type of control map ('canny' or 'depth')
|
| 23 |
+
limit: Maximum number of samples to process (None for all)
|
| 24 |
+
|
| 25 |
+
Returns:
|
| 26 |
+
Path to the created dataset
|
| 27 |
+
"""
|
| 28 |
+
import os
|
| 29 |
+
import json
|
| 30 |
+
|
| 31 |
+
# Create output directories
|
| 32 |
+
dataset_dir = output_dir
|
| 33 |
+
images_dir = os.path.join(dataset_dir, "images")
|
| 34 |
+
controls_dir = os.path.join(dataset_dir, "controls")
|
| 35 |
+
|
| 36 |
+
os.makedirs(dataset_dir, exist_ok=True)
|
| 37 |
+
os.makedirs(images_dir, exist_ok=True)
|
| 38 |
+
os.makedirs(controls_dir, exist_ok=True)
|
| 39 |
+
|
| 40 |
+
# Prepare metadata
|
| 41 |
+
metadata = []
|
| 42 |
+
|
| 43 |
+
total_samples = len(dataset)
|
| 44 |
+
print(f"Processing {total_samples} samples for ControlNet {preprocessor.cn_type} dataset...")
|
| 45 |
+
# Process each sample
|
| 46 |
+
for i, sample in enumerate(
|
| 47 |
+
tqdm(dataset, total=total_samples, desc="Processing samples")
|
| 48 |
+
):
|
| 49 |
+
input_image = sample["image"]
|
| 50 |
+
prompt = ""
|
| 51 |
+
if "answer" in sample and sample["answer"]:
|
| 52 |
+
for ans in sample["answer"]:
|
| 53 |
+
prompt += (ans+" ")
|
| 54 |
+
# for debug only
|
| 55 |
+
# if i < 6:
|
| 56 |
+
# print(f"prompt: {prompt}")
|
| 57 |
+
# if i == 5:
|
| 58 |
+
# return
|
| 59 |
+
# Process image with ControlNet preprocessor
|
| 60 |
+
try:
|
| 61 |
+
control_map = preprocessor.process(image=input_image)
|
| 62 |
+
|
| 63 |
+
# Save original image and control map
|
| 64 |
+
image_filename = f"image_{i:06d}.jpg"
|
| 65 |
+
control_filename = f"control_{i:06d}.jpg"
|
| 66 |
+
|
| 67 |
+
input_image.save(os.path.join(images_dir, image_filename))
|
| 68 |
+
control_map.save(os.path.join(controls_dir, control_filename))
|
| 69 |
+
|
| 70 |
+
# Add to metadata
|
| 71 |
+
metadata.append(
|
| 72 |
+
{
|
| 73 |
+
"id": i,
|
| 74 |
+
"prompt": prompt,
|
| 75 |
+
"image": f"images/{image_filename}",
|
| 76 |
+
"control": f"controls/{control_filename}",
|
| 77 |
+
}
|
| 78 |
+
)
|
| 79 |
+
except Exception as e:
|
| 80 |
+
print(f"Error processing sample {i}: {e}")
|
| 81 |
+
continue
|
| 82 |
+
|
| 83 |
+
# Save metadata
|
| 84 |
+
metadata_path = os.path.join(dataset_dir, "metadata.json")
|
| 85 |
+
with open(metadata_path, "w") as f:
|
| 86 |
+
json.dump(metadata, f, indent=2)
|
| 87 |
+
|
| 88 |
+
print(f"Dataset created at: {dataset_dir}")
|
| 89 |
+
print(f"Total processed samples: {len(metadata)}")
|
| 90 |
+
return dataset_dir
|
| 91 |
+
|
| 92 |
+
def parse_args():
|
| 93 |
+
import argparse
|
| 94 |
+
# Set up command line arguments
|
| 95 |
+
parser = argparse.ArgumentParser(description="Create ControlNet dataset from COCO")
|
| 96 |
+
parser.add_argument(
|
| 97 |
+
"--output_dir",
|
| 98 |
+
type=str,
|
| 99 |
+
default="../dataset/controlnet_datasets",
|
| 100 |
+
help="Directory to save the processed dataset",
|
| 101 |
+
)
|
| 102 |
+
parser.add_argument(
|
| 103 |
+
"--cn_type",
|
| 104 |
+
type=str,
|
| 105 |
+
default="canny",
|
| 106 |
+
choices=["canny", "depth"],
|
| 107 |
+
help="Type of control map to generate",
|
| 108 |
+
)
|
| 109 |
+
parser.add_argument(
|
| 110 |
+
"--sample_size", type=int, default=5000, help="Maximum number of samples to process"
|
| 111 |
+
)
|
| 112 |
+
parser.add_argument(
|
| 113 |
+
"--enable_blur",
|
| 114 |
+
action="store_true",
|
| 115 |
+
help="Enable Gaussian blur for Canny edge detection",
|
| 116 |
+
)
|
| 117 |
+
parser.add_argument(
|
| 118 |
+
"--dataset",
|
| 119 |
+
type=str,
|
| 120 |
+
default="COCO-Caption2017",
|
| 121 |
+
help="Dataset to use (default: COCO-Caption2017)",
|
| 122 |
+
)
|
| 123 |
+
parser.add_argument(
|
| 124 |
+
"--split", type=str, default="val", help="Dataset split to use (default: val)"
|
| 125 |
+
)
|
| 126 |
+
parser.add_argument(
|
| 127 |
+
"--blur_kernel_size",
|
| 128 |
+
type=int,
|
| 129 |
+
default=3,
|
| 130 |
+
help="Kernel size used to blur the image before Canny edge detection (must be odd)",
|
| 131 |
+
)
|
| 132 |
+
parser.add_argument("--enable_no_prompt", action="store_true")
|
| 133 |
+
parser.add_argument("--random_sample", action="store_true")
|
| 134 |
+
return parser.parse_args()
|
| 135 |
+
|
| 136 |
+
if __name__ == "__main__":
|
| 137 |
+
args = parse_args()
|
| 138 |
+
|
| 139 |
+
print("Loading dataset...")
|
| 140 |
+
|
| 141 |
+
# Load the dataset
|
| 142 |
+
try:
|
| 143 |
+
# determine the total number of samples
|
| 144 |
+
dataset = load_dataset(os.path.join("../dataset", args.dataset), split=args.split, trust_remote_code=True)
|
| 145 |
+
# random sample
|
| 146 |
+
if args.sample_size is not None and args.random_sample:
|
| 147 |
+
total_samples = min(args.sample_size, len(dataset))
|
| 148 |
+
indices = random.sample(range(len(dataset)), total_samples)
|
| 149 |
+
dataset = dataset.select(indices) # HuggingFace way
|
| 150 |
+
elif args.sample_size is not None:
|
| 151 |
+
dataset = dataset.select(range(args.sample_size))
|
| 152 |
+
|
| 153 |
+
dataset.name = args.dataset
|
| 154 |
+
print(f"Number of examples: {len(dataset)}")
|
| 155 |
+
print("Dataset features:", dataset.features)
|
| 156 |
+
except Exception as e:
|
| 157 |
+
print(f"Error loading dataset: {e}")
|
| 158 |
+
print(
|
| 159 |
+
"Please ensure you have an internet connection and the dataset name is correct."
|
| 160 |
+
)
|
| 161 |
+
exit()
|
| 162 |
+
|
| 163 |
+
# Initialize preprocessor
|
| 164 |
+
preprocessor = ControlNetPreprocessor(
|
| 165 |
+
enable_blur=args.enable_blur, blur_kernel_size=args.blur_kernel_size, cn_type=args.cn_type
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
# Create ControlNet dataset
|
| 169 |
+
dataset_dir = create_dataset(
|
| 170 |
+
preprocessor=preprocessor,
|
| 171 |
+
dataset=dataset,
|
| 172 |
+
output_dir=os.path.join(args.output_dir, f"{args.dataset}-{args.cn_type}"),
|
| 173 |
+
enable_no_prompt=args.enable_no_prompt,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
print("Done!")
|
dataset_scripts/dci/dci_dataset.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataset.caption_control_dataset import CaptionControlDataset
|
| 2 |
+
|
| 3 |
+
DCIDataset = CaptionControlDataset
|
| 4 |
+
|
| 5 |
+
if __name__ == "__main__":
|
| 6 |
+
dataset = DCIDataset(path="../dataset/controlnet_datasets/DCI-30K-canny", cache_size=16)
|
| 7 |
+
data_loader = dataset.get_dataloader(batch_size=1)
|
| 8 |
+
|
| 9 |
+
for i, batch in enumerate(data_loader):
|
| 10 |
+
prompt, image, control = batch[0]
|
| 11 |
+
print("prompt:", prompt)
|
| 12 |
+
print("image:", image)
|
| 13 |
+
print("control:", control)
|
| 14 |
+
print("--------------")
|
| 15 |
+
if i > 10:
|
| 16 |
+
break
|
dataset_scripts/dci/preprocess.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
import re
|
| 3 |
+
import os
|
| 4 |
+
from tqdm import tqdm # To measure processing time
|
| 5 |
+
from backend.torch.utils import load_image
|
| 6 |
+
from dataset.processor import ControlNetPreprocessor
|
| 7 |
+
import random
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def create_dataset(
|
| 11 |
+
preprocessor,
|
| 12 |
+
dataset_dir,
|
| 13 |
+
output_dir,
|
| 14 |
+
enable_extra_caption=True,
|
| 15 |
+
sample_size=5000,
|
| 16 |
+
):
|
| 17 |
+
"""
|
| 18 |
+
Creates a ControlNet dataset by processing images from a source dataset.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
preprocessor: The ControlNetPreprocessor instance
|
| 22 |
+
dataset_dir: The source dataset (e.g., COCO)
|
| 23 |
+
output_dir: Directory to save the processed dataset
|
| 24 |
+
cn_type: Type of control map ('canny' or 'depth')
|
| 25 |
+
limit: Maximum number of samples to process (None for all)
|
| 26 |
+
|
| 27 |
+
Returns:
|
| 28 |
+
Path to the created dataset
|
| 29 |
+
"""
|
| 30 |
+
import os
|
| 31 |
+
import json
|
| 32 |
+
|
| 33 |
+
# Create output directories
|
| 34 |
+
images_dir = os.path.join(output_dir, "images")
|
| 35 |
+
controls_dir = os.path.join(output_dir, "controls")
|
| 36 |
+
|
| 37 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 38 |
+
os.makedirs(images_dir, exist_ok=True)
|
| 39 |
+
os.makedirs(controls_dir, exist_ok=True)
|
| 40 |
+
|
| 41 |
+
# Prepare metadata
|
| 42 |
+
metadata = []
|
| 43 |
+
|
| 44 |
+
def list_matching_file_paths_regex(folder_path, pattern):
|
| 45 |
+
regex = re.compile(pattern)
|
| 46 |
+
return [
|
| 47 |
+
os.path.join(folder_path, f)
|
| 48 |
+
for f in os.listdir(folder_path)
|
| 49 |
+
if os.path.isfile(os.path.join(folder_path, f)) and regex.fullmatch(f)
|
| 50 |
+
]
|
| 51 |
+
|
| 52 |
+
origin_data = list_matching_file_paths_regex(
|
| 53 |
+
os.path.join(dataset_dir, "annotations"), r".*\.json"
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
total_samples = len(origin_data) if sample_size is None else min(sample_size, len(origin_data))
|
| 57 |
+
origin_data = random.sample(origin_data, total_samples)
|
| 58 |
+
print(f"Processing {total_samples} samples for ControlNet {preprocessor.cn_type} dataset...")
|
| 59 |
+
|
| 60 |
+
for i, orig in enumerate(
|
| 61 |
+
tqdm(origin_data, total=total_samples, desc="Processing samples")
|
| 62 |
+
):
|
| 63 |
+
with open(orig, "r") as file:
|
| 64 |
+
d = json.load(file)
|
| 65 |
+
|
| 66 |
+
if "image" not in d:
|
| 67 |
+
raise KeyError()
|
| 68 |
+
|
| 69 |
+
input_image = load_image(os.path.join(dataset_dir, "photos", d["image"]))
|
| 70 |
+
prompt = d.get("short_caption", "")
|
| 71 |
+
|
| 72 |
+
if enable_extra_caption and "extra_caption" in d:
|
| 73 |
+
prompt = prompt + " " + d["extra_caption"]
|
| 74 |
+
|
| 75 |
+
try:
|
| 76 |
+
control_map = preprocessor.process(image=input_image)
|
| 77 |
+
|
| 78 |
+
# Save original image and control map
|
| 79 |
+
image_filename = f"image_{i:06d}.jpg"
|
| 80 |
+
control_filename = f"control_{i:06d}.jpg"
|
| 81 |
+
|
| 82 |
+
input_image.save(os.path.join(images_dir, image_filename))
|
| 83 |
+
control_map.save(os.path.join(controls_dir, control_filename))
|
| 84 |
+
|
| 85 |
+
# Add to metadata
|
| 86 |
+
metadata.append(
|
| 87 |
+
{
|
| 88 |
+
"id": i,
|
| 89 |
+
"prompt": prompt,
|
| 90 |
+
"image": f"images/{image_filename}",
|
| 91 |
+
"control": f"controls/{control_filename}",
|
| 92 |
+
}
|
| 93 |
+
)
|
| 94 |
+
except Exception as e:
|
| 95 |
+
print(f"Error processing sample {i}: {e}")
|
| 96 |
+
continue
|
| 97 |
+
|
| 98 |
+
# Save metadata
|
| 99 |
+
metadata_path = os.path.join(output_dir, "metadata.json")
|
| 100 |
+
with open(metadata_path, "w") as f:
|
| 101 |
+
json.dump(metadata, f, indent=2)
|
| 102 |
+
|
| 103 |
+
print(f"Dataset created at: {output_dir}")
|
| 104 |
+
print(f"Total processed samples: {len(metadata)}")
|
| 105 |
+
return output_dir
|
| 106 |
+
|
| 107 |
+
def parse_args():
|
| 108 |
+
import argparse
|
| 109 |
+
# Set up command line arguments
|
| 110 |
+
parser = argparse.ArgumentParser(description="Create ControlNet dataset from COCO")
|
| 111 |
+
parser.add_argument(
|
| 112 |
+
"--output_dir",
|
| 113 |
+
type=str,
|
| 114 |
+
default="../dataset/controlnet_datasets",
|
| 115 |
+
help="Directory to save the processed dataset",
|
| 116 |
+
)
|
| 117 |
+
parser.add_argument(
|
| 118 |
+
"--cn_type",
|
| 119 |
+
type=str,
|
| 120 |
+
default="canny",
|
| 121 |
+
choices=["canny", "depth"],
|
| 122 |
+
help="Type of control map to generate",
|
| 123 |
+
)
|
| 124 |
+
parser.add_argument(
|
| 125 |
+
"--enable_blur",
|
| 126 |
+
action="store_true",
|
| 127 |
+
help="Enable Gaussian blur for Canny edge detection",
|
| 128 |
+
)
|
| 129 |
+
parser.add_argument(
|
| 130 |
+
"--dataset",
|
| 131 |
+
type=str,
|
| 132 |
+
default="DCI",
|
| 133 |
+
help="Dataset to use (default: DCI)",
|
| 134 |
+
)
|
| 135 |
+
parser.add_argument(
|
| 136 |
+
"--dataset_dir",
|
| 137 |
+
type=str,
|
| 138 |
+
default="../dataset/densely_captioned_images",
|
| 139 |
+
help="Dataset to use (default: densely_captioned_images)",
|
| 140 |
+
)
|
| 141 |
+
parser.add_argument(
|
| 142 |
+
"--blur_kernel_size",
|
| 143 |
+
type=int,
|
| 144 |
+
default=3,
|
| 145 |
+
help="Kernel size used to blur the image before Canny edge detection (must be odd)",
|
| 146 |
+
)
|
| 147 |
+
parser.add_argument(
|
| 148 |
+
"--sample_size", type=int, default=5000, help="Maximum number of samples to process"
|
| 149 |
+
)
|
| 150 |
+
parser.add_argument("--disable_extra_caption", action="store_true")
|
| 151 |
+
args = parser.parse_args()
|
| 152 |
+
return args
|
| 153 |
+
|
| 154 |
+
if __name__ == "__main__":
|
| 155 |
+
args = parse_args()
|
| 156 |
+
|
| 157 |
+
# Initialize preprocessor
|
| 158 |
+
preprocessor = ControlNetPreprocessor(
|
| 159 |
+
enable_blur=args.enable_blur, blur_kernel_size=args.blur_kernel_size, cn_type=args.cn_type
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
# Create ControlNet dataset
|
| 163 |
+
dataset_dir = create_dataset(
|
| 164 |
+
preprocessor=preprocessor,
|
| 165 |
+
dataset_dir=args.dataset_dir,
|
| 166 |
+
output_dir=os.path.join(args.output_dir, f"{args.dataset}-{args.cn_type}"),
|
| 167 |
+
enable_extra_caption=(not args.disable_extra_caption),
|
| 168 |
+
sample_size=args.sample_size,
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
print(f"\nControlNet dataset created at: {dataset_dir}")
|
| 172 |
+
print("Done!")
|
dataset_scripts/mjhq/mjhq_dataset.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataset.caption_control_dataset import CaptionControlDataset
|
| 2 |
+
|
| 3 |
+
MJHQDataset = CaptionControlDataset
|
| 4 |
+
|
| 5 |
+
if __name__ == "__main__":
|
| 6 |
+
dataset = MJHQDataset(
|
| 7 |
+
path="../dataset/controlnet_datasets/MJHQ-30K-canny", cache_size=16
|
| 8 |
+
)
|
| 9 |
+
data_loader = dataset.get_dataloader(batch_size=1)
|
| 10 |
+
|
| 11 |
+
for i, batch in enumerate(data_loader):
|
| 12 |
+
prompt, image, control = batch[0]
|
| 13 |
+
print("prompt:", prompt)
|
| 14 |
+
print("image:", image)
|
| 15 |
+
print("control:", control)
|
| 16 |
+
print("--------------")
|
| 17 |
+
if i > 10:
|
| 18 |
+
break
|
dataset_scripts/mjhq/preprocess.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from tqdm import tqdm # To measure processing time
|
| 2 |
+
from dataset.processor import ControlNetPreprocessor
|
| 3 |
+
from datasets import load_dataset
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import os
|
| 6 |
+
import json
|
| 7 |
+
import random
|
| 8 |
+
import shutil
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def create_dataset(
|
| 12 |
+
preprocessor,
|
| 13 |
+
input_dir,
|
| 14 |
+
output_dir,
|
| 15 |
+
samples_per_category=500,
|
| 16 |
+
):
|
| 17 |
+
"""
|
| 18 |
+
Create a dataset for ControlNet from the specified dataset directory.
|
| 19 |
+
Args:
|
| 20 |
+
input_dir (str): Path to the input dataset directory.
|
| 21 |
+
output_dir (str): Path to the output directory containing images and metadata.
|
| 22 |
+
Returns:
|
| 23 |
+
str: Path to the created dataset directory.
|
| 24 |
+
"""
|
| 25 |
+
ORIGINAL_METADATA_FILE = "meta_data.json"
|
| 26 |
+
CATEGORIES = [
|
| 27 |
+
'animals', 'art', 'fashion', 'food', 'indoor',
|
| 28 |
+
'landscape', 'logo', 'people', 'plants', 'vehicles'
|
| 29 |
+
]
|
| 30 |
+
# Create output directories
|
| 31 |
+
images_output_dir = os.path.join(output_dir, "images")
|
| 32 |
+
controls_output_dir = os.path.join(output_dir, "controls")
|
| 33 |
+
|
| 34 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 35 |
+
os.makedirs(images_output_dir, exist_ok=True)
|
| 36 |
+
os.makedirs(controls_output_dir, exist_ok=True)
|
| 37 |
+
|
| 38 |
+
# Prepare metadata
|
| 39 |
+
metadata = []
|
| 40 |
+
|
| 41 |
+
# read metainfo from dataset_dir
|
| 42 |
+
try:
|
| 43 |
+
with open(os.path.join(input_dir, ORIGINAL_METADATA_FILE), 'r', encoding='utf-8') as f:
|
| 44 |
+
original_metadata = json.load(f)
|
| 45 |
+
except FileNotFoundError:
|
| 46 |
+
print(f"ERROR: Original metadata file not found at {os.path.join(input_dir, ORIGINAL_METADATA_FILE)}")
|
| 47 |
+
print("Please ensure the path is correct and the file exists.")
|
| 48 |
+
return
|
| 49 |
+
except json.JSONDecodeError:
|
| 50 |
+
print(f"ERROR: Could not decode JSON from {os.path.join(input_dir, ORIGINAL_METADATA_FILE)}. Is it a valid JSON file?")
|
| 51 |
+
return
|
| 52 |
+
|
| 53 |
+
# Iterate through categories to sample and copy images
|
| 54 |
+
id = 0
|
| 55 |
+
for category in CATEGORIES:
|
| 56 |
+
print(f"\nProcessing category: {category}...")
|
| 57 |
+
|
| 58 |
+
original_category_path = os.path.join(input_dir, category)
|
| 59 |
+
|
| 60 |
+
if not os.path.isdir(original_category_path):
|
| 61 |
+
print(f" WARNING: Original category folder not found: {original_category_path}. Skipping.")
|
| 62 |
+
continue
|
| 63 |
+
|
| 64 |
+
# List all image files in the original category folder
|
| 65 |
+
try:
|
| 66 |
+
all_images_in_category = [
|
| 67 |
+
f for f in os.listdir(original_category_path)
|
| 68 |
+
]
|
| 69 |
+
except FileNotFoundError:
|
| 70 |
+
print(f" ERROR: Could not list files in {original_category_path}. Check permissions or path.")
|
| 71 |
+
continue
|
| 72 |
+
|
| 73 |
+
if not all_images_in_category:
|
| 74 |
+
print(f" WARNING: No image files found in {original_category_path} for category {category}. Skipping.")
|
| 75 |
+
continue
|
| 76 |
+
|
| 77 |
+
print(f" Found {len(all_images_in_category)} images in original '{category}' folder.")
|
| 78 |
+
|
| 79 |
+
# Randomly select SAMPLES_PER_CATEGORY image filenames
|
| 80 |
+
if len(all_images_in_category) < samples_per_category:
|
| 81 |
+
print(f" WARNING: Category '{category}' has only {len(all_images_in_category)} images, "
|
| 82 |
+
f"which is less than the required {samples_per_category}. Taking all available images.")
|
| 83 |
+
sampled_image_filenames_with_ext = all_images_in_category
|
| 84 |
+
else:
|
| 85 |
+
sampled_image_filenames_with_ext = random.sample(all_images_in_category, samples_per_category)
|
| 86 |
+
|
| 87 |
+
print(f" Sampling {len(sampled_image_filenames_with_ext)} images for '{category}'.")
|
| 88 |
+
|
| 89 |
+
for img_filename_with_ext in sampled_image_filenames_with_ext:
|
| 90 |
+
img_base_filename = os.path.splitext(img_filename_with_ext)[0]
|
| 91 |
+
if img_base_filename in original_metadata:
|
| 92 |
+
image_filename = f"image_{id:06d}.jpg"
|
| 93 |
+
src_img_path = os.path.join(original_category_path, img_filename_with_ext)
|
| 94 |
+
dst_img_path = os.path.join(images_output_dir, image_filename) # Destination is now the shared folder
|
| 95 |
+
|
| 96 |
+
# Copy the image file to the single 'images' folder
|
| 97 |
+
try:
|
| 98 |
+
shutil.copy2(src_img_path, dst_img_path) # copy2 preserves metadata
|
| 99 |
+
except Exception as e:
|
| 100 |
+
print(f" ERROR copying {src_img_path} to {dst_img_path}: {e}")
|
| 101 |
+
continue # Skip this image if copying fails
|
| 102 |
+
|
| 103 |
+
# Save original image and control map
|
| 104 |
+
control_map = preprocessor.process(image=Image.open(dst_img_path))
|
| 105 |
+
control_filename = f"control_{id:06d}.jpg"
|
| 106 |
+
control_map.save(os.path.join(controls_output_dir, control_filename))
|
| 107 |
+
|
| 108 |
+
# Get the prompt from original metadata
|
| 109 |
+
prompt = original_metadata[img_base_filename].get("prompt", "")
|
| 110 |
+
|
| 111 |
+
# Add to metadata
|
| 112 |
+
metadata.append(
|
| 113 |
+
{
|
| 114 |
+
"id": id,
|
| 115 |
+
"prompt": prompt,
|
| 116 |
+
"image": f"images/{image_filename}",
|
| 117 |
+
"control": f"controls/{control_filename}",
|
| 118 |
+
}
|
| 119 |
+
)
|
| 120 |
+
id += 1
|
| 121 |
+
else:
|
| 122 |
+
print(f" WARNING: Metadata key '{img_base_filename}' (from file '{img_filename_with_ext}') "
|
| 123 |
+
f"not found in original_metadata.json. Skipping this image.")
|
| 124 |
+
|
| 125 |
+
# 4. Save new metadata
|
| 126 |
+
# Save metadata
|
| 127 |
+
metadata_path = os.path.join(output_dir, "metadata.json")
|
| 128 |
+
with open(metadata_path, "w") as f:
|
| 129 |
+
json.dump(metadata, f, indent=2)
|
| 130 |
+
print(f"Dataset created at: {output_dir}")
|
| 131 |
+
print(f"Total processed samples: {len(metadata)}")
|
| 132 |
+
|
| 133 |
+
return output_dir
|
| 134 |
+
|
| 135 |
+
def parse_args():
|
| 136 |
+
import argparse
|
| 137 |
+
# Set up command line arguments
|
| 138 |
+
parser = argparse.ArgumentParser(description="Create ControlNet dataset from datasets")
|
| 139 |
+
parser.add_argument(
|
| 140 |
+
"--cn_type",
|
| 141 |
+
type=str,
|
| 142 |
+
default="canny",
|
| 143 |
+
choices=["canny", "depth"],
|
| 144 |
+
help="Type of control map to generate",
|
| 145 |
+
)
|
| 146 |
+
parser.add_argument(
|
| 147 |
+
"--enable_blur",
|
| 148 |
+
action="store_true",
|
| 149 |
+
help="Enable Gaussian blur for Canny edge detection",
|
| 150 |
+
)
|
| 151 |
+
parser.add_argument(
|
| 152 |
+
"--dataset",
|
| 153 |
+
type=str,
|
| 154 |
+
default="MJHQ-30K",
|
| 155 |
+
help="Dataset to use (default: MJHQ-30K)",
|
| 156 |
+
)
|
| 157 |
+
parser.add_argument(
|
| 158 |
+
"--dataset_dir",
|
| 159 |
+
type=str,
|
| 160 |
+
default="../dataset",
|
| 161 |
+
help="Dataset to use (default: COCO-Caption2017)",
|
| 162 |
+
)
|
| 163 |
+
parser.add_argument(
|
| 164 |
+
"--output_dir",
|
| 165 |
+
type=str,
|
| 166 |
+
default="../dataset/controlnet_datasets",
|
| 167 |
+
help="Directory to save the processed dataset",
|
| 168 |
+
)
|
| 169 |
+
parser.add_argument(
|
| 170 |
+
"--blur_kernel_size",
|
| 171 |
+
type=int,
|
| 172 |
+
default=3,
|
| 173 |
+
help="Kernel size used to blur the image before Canny edge detection (must be odd)",
|
| 174 |
+
)
|
| 175 |
+
parser.add_argument("--enable_no_prompt", action="store_true")
|
| 176 |
+
return parser.parse_args()
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
if __name__ == "__main__":
|
| 181 |
+
args = parse_args()
|
| 182 |
+
# Initialize preprocessor
|
| 183 |
+
preprocessor = ControlNetPreprocessor(
|
| 184 |
+
enable_blur=args.enable_blur, blur_kernel_size=args.blur_kernel_size,cn_type=args.cn_type
|
| 185 |
+
)
|
| 186 |
+
# Create anno dataset
|
| 187 |
+
control_dataset_dir = create_dataset(
|
| 188 |
+
preprocessor=preprocessor,
|
| 189 |
+
input_dir=os.path.join(args.dataset_dir, args.dataset),
|
| 190 |
+
output_dir=os.path.join(args.output_dir, f"{args.dataset}-{args.cn_type}"),
|
| 191 |
+
samples_per_category=500, # Number of samples per category
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
print(f"\nControlNet dataset created at: {control_dataset_dir}")
|
| 195 |
+
print("Done!")
|
dataset_scripts/processor.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import numpy as np
|
| 4 |
+
import cv2
|
| 5 |
+
import torch
|
| 6 |
+
from transformers import DPTFeatureExtractor, DPTForDepthEstimation
|
| 7 |
+
|
| 8 |
+
# TODO: Add self.cn_type to control the control map type
|
| 9 |
+
# Then check the relative imports of this processor in benchmark
|
| 10 |
+
class ControlNetPreprocessor:
|
| 11 |
+
"""
|
| 12 |
+
A class to preprocess images for ControlNet input (Canny edges, Depth maps).
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
def __init__(self, enable_blur=True, blur_kernel_size=3, cn_type="canny", device=None):
|
| 16 |
+
"""
|
| 17 |
+
Initializes the preprocessor, loading necessary models.
|
| 18 |
+
Args:
|
| 19 |
+
device (str, optional): The device to run models on ('cuda', 'cpu').
|
| 20 |
+
Defaults to 'cuda' if available, else 'cpu'.
|
| 21 |
+
"""
|
| 22 |
+
print("Initializing ControlNetPreprocessor...")
|
| 23 |
+
self.cn_type = cn_type
|
| 24 |
+
# --- Device Setup ---
|
| 25 |
+
if device is None:
|
| 26 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 27 |
+
else:
|
| 28 |
+
self.device = torch.device(device)
|
| 29 |
+
print(f"Using device: {self.device}")
|
| 30 |
+
|
| 31 |
+
# --- Canny Edge Setup ---
|
| 32 |
+
if self.cn_type == "canny":
|
| 33 |
+
|
| 34 |
+
self.canny_low_threshold = 100
|
| 35 |
+
self.canny_high_threshold = 200
|
| 36 |
+
self.canny_blur_kernel_size = blur_kernel_size # Must be odd
|
| 37 |
+
self.enable_blur = enable_blur
|
| 38 |
+
|
| 39 |
+
assert (
|
| 40 |
+
self.canny_blur_kernel_size % 2 != 0
|
| 41 |
+
), "Warning: Blur kernel size must be odd."
|
| 42 |
+
print("Canny edge detector configured.")
|
| 43 |
+
|
| 44 |
+
# --- Depth Estimation Setup ---
|
| 45 |
+
# Using Intel's DPT model (Dense Prediction Transformer) via Hugging Face
|
| 46 |
+
elif self.cn_type == "depth":
|
| 47 |
+
depth_model_name = "Intel/dpt-large" # Or try "Intel/dpt-hybrid-midas" for potentially faster/different results
|
| 48 |
+
print(f"Loading depth estimation model: {depth_model_name}...")
|
| 49 |
+
start_time = time.time()
|
| 50 |
+
try:
|
| 51 |
+
self.depth_feature_extractor = DPTFeatureExtractor.from_pretrained(
|
| 52 |
+
depth_model_name
|
| 53 |
+
)
|
| 54 |
+
self.depth_model = DPTForDepthEstimation.from_pretrained(depth_model_name)
|
| 55 |
+
self.depth_model.to(self.device)
|
| 56 |
+
self.depth_model.eval() # Set model to evaluation mode
|
| 57 |
+
print(
|
| 58 |
+
f"Depth model loaded to {self.device} in {time.time() - start_time:.2f} seconds."
|
| 59 |
+
)
|
| 60 |
+
except Exception as e:
|
| 61 |
+
print(f"Error loading depth model: {e}")
|
| 62 |
+
print("Please ensure 'transformers' and 'torch' are installed correctly.")
|
| 63 |
+
# Optionally handle the error, e.g., disable depth processing
|
| 64 |
+
self.depth_model = None
|
| 65 |
+
self.depth_feature_extractor = None
|
| 66 |
+
|
| 67 |
+
print("Preprocessor initialization complete.")
|
| 68 |
+
|
| 69 |
+
def _to_numpy(self, image: Image.Image) -> np.ndarray:
|
| 70 |
+
"""Converts PIL Image to NumPy array (RGB)."""
|
| 71 |
+
return np.array(image.convert("RGB"))
|
| 72 |
+
|
| 73 |
+
def get_canny_map(self, image: Image.Image) -> Image.Image:
|
| 74 |
+
"""
|
| 75 |
+
Generates a Canny edge map from the input image.
|
| 76 |
+
Args:
|
| 77 |
+
image (PIL.Image.Image): Input image.
|
| 78 |
+
Returns:
|
| 79 |
+
PIL.Image.Image: Grayscale Canny edge map.
|
| 80 |
+
"""
|
| 81 |
+
if not isinstance(image, Image.Image):
|
| 82 |
+
raise TypeError("Input must be a PIL Image.")
|
| 83 |
+
|
| 84 |
+
image_np = self._to_numpy(image)
|
| 85 |
+
# 1. Convert to grayscale for Canny
|
| 86 |
+
image_gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
|
| 87 |
+
|
| 88 |
+
# 2. Edeg detection. Apply Gaussian Blur to reduce noise and fine details if needed
|
| 89 |
+
if self.enable_blur:
|
| 90 |
+
kernel_size = (self.canny_blur_kernel_size, self.canny_blur_kernel_size)
|
| 91 |
+
image_blurred = cv2.GaussianBlur(image_gray, kernel_size, 0)
|
| 92 |
+
edges = cv2.Canny(
|
| 93 |
+
image_blurred, self.canny_low_threshold, self.canny_high_threshold
|
| 94 |
+
)
|
| 95 |
+
else:
|
| 96 |
+
edges = cv2.Canny(
|
| 97 |
+
image_gray, self.canny_low_threshold, self.canny_high_threshold
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
# ControlNet often expects edges as white lines on black background
|
| 101 |
+
# Invert if needed (some models might expect black lines on white)
|
| 102 |
+
# edges = 255 - edges
|
| 103 |
+
return Image.fromarray(edges).convert("L") # Ensure grayscale PIL image
|
| 104 |
+
|
| 105 |
+
def get_depth_map(self, image: Image.Image) -> Image.Image | None:
|
| 106 |
+
"""
|
| 107 |
+
Generates a depth map from the input image using a DPT model.
|
| 108 |
+
Args:
|
| 109 |
+
image (PIL.Image.Image): Input image.
|
| 110 |
+
Returns:
|
| 111 |
+
PIL.Image.Image | None: Grayscale depth map (closer is often brighter/whiter,
|
| 112 |
+
but depends on normalization), or None if model failed to load.
|
| 113 |
+
"""
|
| 114 |
+
if self.depth_model is None or self.depth_feature_extractor is None:
|
| 115 |
+
print("Depth model not available.")
|
| 116 |
+
return None
|
| 117 |
+
if not isinstance(image, Image.Image):
|
| 118 |
+
raise TypeError("Input must be a PIL Image.")
|
| 119 |
+
|
| 120 |
+
original_size = image.size # W, H
|
| 121 |
+
|
| 122 |
+
# Prepare image for the model
|
| 123 |
+
inputs = self.depth_feature_extractor(images=image, return_tensors="pt")
|
| 124 |
+
pixel_values = inputs.pixel_values.to(self.device)
|
| 125 |
+
|
| 126 |
+
# Inference
|
| 127 |
+
with torch.no_grad():
|
| 128 |
+
outputs = self.depth_model(pixel_values)
|
| 129 |
+
predicted_depth = outputs.predicted_depth # This is raw output (logits)
|
| 130 |
+
|
| 131 |
+
# Interpolate prediction to original image size
|
| 132 |
+
# Note: PIL size is (W, H), interpolate expects (H, W)
|
| 133 |
+
prediction = torch.nn.functional.interpolate(
|
| 134 |
+
predicted_depth.unsqueeze(1),
|
| 135 |
+
size=original_size[::-1], # Reverse to (H, W)
|
| 136 |
+
mode="bicubic",
|
| 137 |
+
align_corners=False,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
# Normalize and format output
|
| 141 |
+
output = prediction.squeeze().cpu().numpy()
|
| 142 |
+
# Normalize to 0-1 range
|
| 143 |
+
formatted = (output - np.min(output)) / (np.max(output) - np.min(output))
|
| 144 |
+
# Scale to 0-255 and convert to uint8 grayscale image
|
| 145 |
+
depth_map_np = (formatted * 255).astype(np.uint8)
|
| 146 |
+
depth_map_image = Image.fromarray(depth_map_np).convert(
|
| 147 |
+
"L"
|
| 148 |
+
) # Ensure grayscale PIL image
|
| 149 |
+
|
| 150 |
+
return depth_map_image
|
| 151 |
+
|
| 152 |
+
def process(
|
| 153 |
+
self, image: Image.Image
|
| 154 |
+
) -> tuple[Image.Image | None, Image.Image | None]:
|
| 155 |
+
"""
|
| 156 |
+
Generates both Canny edge map and depth map for the input image.
|
| 157 |
+
Args:
|
| 158 |
+
image (PIL.Image.Image): Input image.
|
| 159 |
+
Returns:
|
| 160 |
+
tuple[Image.Image | None, Image.Image | None]: (canny_map, depth_map)
|
| 161 |
+
"""
|
| 162 |
+
if self.cn_type == "canny":
|
| 163 |
+
res_map = self.get_canny_map(image)
|
| 164 |
+
elif self.cn_type == "depth":
|
| 165 |
+
res_map = self.get_depth_map(image)
|
| 166 |
+
else:
|
| 167 |
+
print("Type does not exist")
|
| 168 |
+
return res_map
|