Skip to content

Commit a85f351

Browse files
committed
Initial commit
0 parents  commit a85f351

99 files changed

Lines changed: 11256 additions & 0 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.gitignore

Lines changed: 587 additions & 0 deletions
Large diffs are not rendered by default.

README.md

Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
# VisualSplit
2+
3+
> **TL;DR** — Learn an interpretable image representation by **splitting** an image into **edge**, **color-segmentation**, and **gray-level histogram** descriptors, then **reconstruct** it from only those descriptors. Useful for reconstruction/restoration and controllable editing.
4+
5+
<p align="left">
6+
<a href="https://pypi.org/project/torch/"><img src="https://img.shields.io/badge/PyTorch-2.2%2B-ee4c2c" alt="PyTorch"></a>
7+
<a href="./LICENSE"><img src="https://img.shields.io/badge/License-Apache--2.0-blue.svg" alt="License: Apache-2.0"></a>
8+
<a href="https://huggingface.co/quchenyuan/VisualSplit"><img src="https://img.shields.io/badge/Weights-HuggingFace-yellow.svg" alt="HuggingFace Weights"></a>
9+
</p>
10+
11+
---
12+
13+
## Table of Contents
14+
- [Highlights](#highlights)
15+
- [What's inside](#whats-inside)
16+
- [Install](#install)
17+
- [Quickstart](#quickstart)
18+
- [Load pretrained & reconstruct](#load-pretrained--reconstruct)
19+
- [Train from scratch](#train-from-scratch)
20+
- [Validate restoration](#validate-restoration)
21+
- [Config & Data](#config--data)
22+
- [Roadmap](#roadmap)
23+
- [FAQ / Troubleshooting](#faq--troubleshooting)
24+
- [License](#license)
25+
- [Acknowledgements](#acknowledgements)
26+
27+
---
28+
29+
## Highlights
30+
- **Interpretable**: decouples geometry, color regions, and global tone into separate, human-understandable descriptors.
31+
- **Mask-free pretraining**: descriptors themselves act as “information-sparse” inputs; no patch masking tricks.
32+
- **Pretrained checkpoint**: ready-to-use weights on HF → **[quchenyuan/VisualSplit](https://huggingface.co/quchenyuan/VisualSplit)**.
33+
- **Restoration validation**: basic examples to evaluate reconstruction/PSNR/SSIM on your data.
34+
35+
---
36+
37+
## What's inside
38+
39+
```
40+
VisualSplit/
41+
├─ visualsplit/
42+
│ ├─ models/
43+
│ │ └─ CrossViT.py # ViT-based multi-modal encoder + lightweight decoder
44+
│ ├─ pipeline/
45+
│ │ └─ train_CrossViT.py # self-supervised training (reconstruction objective)
46+
│ ├─ utils/
47+
│ │ └─ feature_extractor.py # edge / color segmentation / gray histogram
48+
│ └─ ...
49+
├─ LICENSE
50+
└─ README.md
51+
```
52+
53+
- **Descriptors**: Sobel edges, K-means color segmentation (LAB), 100-bin gray-level histogram.
54+
- **Encoder**: ViT backbone consumes **edge+seg** as patch tokens; **histogram** enters via global conditioning.
55+
- **Decoder**: lightweight head to reconstruct RGB.
56+
57+
---
58+
59+
## Install
60+
61+
```bash
62+
# clone
63+
git clone https://github.com/HenryQUQ/VisualSplit.git
64+
cd VisualSplit
65+
66+
# (option A) pip editable install
67+
pip install -e .
68+
69+
# (option B) poetry
70+
# poetry install
71+
```
72+
73+
> Requires Python ≥ 3.10, PyTorch ≥ 2.2 (CUDA recommended). See `requirements.txt` / `pyproject.toml` for full deps.
74+
75+
---
76+
77+
## Quickstart
78+
79+
### Load pretrained & reconstruct
80+
81+
```python
82+
import torch
83+
from PIL import Image
84+
from torchvision import transforms
85+
86+
from visualsplit.models.CrossViT import CrossViTForPreTraining, CrossViTConfig
87+
# If your project structure differs, adjust this import path accordingly:
88+
from visualsplit.utils.feature_extractor import FeatureExtractor
89+
90+
# 1) create model (match training config)
91+
config = CrossViTConfig(image_size=224, patch_size=16)
92+
model = CrossViTForPreTraining(config).eval()
93+
94+
# 2) load weights (download from HF manually or via huggingface_hub)
95+
# from huggingface_hub import hf_hub_download
96+
# ckpt_path = hf_hub_download(repo_id="quchenyuan/VisualSplit", filename="visualsplit_vitb.safetensors")
97+
state = torch.load("path/to/VisualSplit_checkpoint.pth", map_location="cpu")
98+
model.load_state_dict(state)
99+
100+
# 3) prepare image & descriptors
101+
image = Image.open("my_test_image.jpg").convert("RGB")
102+
to_tensor = transforms.Compose([transforms.Resize((224, 224)), transforms.ToTensor()])
103+
img = to_tensor(image).unsqueeze(0)
104+
extractor = FeatureExtractor() # returns edge, hist, segmented, (optional ab)
105+
edge, gray_hist, segmented, _ = extractor(img)
106+
107+
# 4) reconstruct
108+
with torch.no_grad():
109+
outputs = model(
110+
source_edge=edge,
111+
source_gray_level_histogram=gray_hist,
112+
source_segmented_rgb=segmented
113+
)
114+
recon = outputs["logits_reshape"].clamp(0, 1) # (1,3,224,224)
115+
116+
# 5) save
117+
transforms.ToPILImage()(recon.squeeze(0)).save("reconstructed.png")
118+
```
119+
120+
### Train from scratch
121+
122+
> Run from repo root to ensure imports work.
123+
124+
```bash
125+
# single GPU
126+
python -m visualsplit.pipeline.train_CrossViT --dataset ImageNet-1k-pure --batch_size 64 --epochs 100 --learning_rate 1.5e-4
127+
128+
# or with accelerate (if configured)
129+
# accelerate launch -m visualsplit.pipeline.train_CrossViT --dataset ImageNet-1k-pure ...
130+
```
131+
132+
The script:
133+
- loads data (HF datasets or your custom loader),
134+
- extracts descriptors on-the-fly (with caching),
135+
- optimizes reconstruction (MSE + LPIPS),
136+
- saves logs/checkpoints (default under `cache/logs/`).
137+
138+
### Validate restoration
139+
140+
Use the pretrained model to **reconstruct** from descriptors extracted on **your degraded images** (e.g., noisy or low-light). Compare outputs vs. ground-truth with PSNR/SSIM using your evaluation pipeline of choice. The same reconstruction snippet above can be adapted into a loop over a dataset to compute metrics.
141+
142+
---
143+
144+
## Config & Data
145+
146+
- **Backbone**: ViT-B by default (`image_size=224`, `patch_size=16`).
147+
- **Descriptors**: LAB→(Sobel on L, 100-bin hist on L, K-means on AB).
148+
- **Dataset**: default uses ImageNet-1K via HF; you can plug in any image folder dataset as long as it yields tensors to `FeatureExtractor`.
149+
- **Hardware**: training prefers ≥16GB GPU; inference works on CPU but is faster on GPU.
150+
151+
---
152+
153+
## Roadmap
154+
155+
- [ ] **Google Colab**: interactive demo (extract descriptors → reconstruct).
156+
- [ ] **HuggingFace Space**: web UI to upload, view descriptors, and reconstruct.
157+
- [x] **Pretrained checkpoint** on HF: https://huggingface.co/quchenyuan/VisualSplit
158+
- [x] **Training script** & **restoration validation** basics.
159+
160+
---
161+
162+
## FAQ / Troubleshooting
163+
164+
**Q: `ImportError: attempted relative import with no known parent package`?**
165+
A: Run from repo root and use module mode:
166+
`python -m visualsplit.pipeline.train_CrossViT ...`
167+
168+
**Q: Where do checkpoints go / how to change?**
169+
A: Check the training script args (save dir/log dir flags) and set your preferred path.
170+
171+
**Q: My reconstruction looks too dark/bright.**
172+
A: Ensure inputs are resized to the training size (default 224) and histogram extraction matches training (100 bins on L channel).
173+
174+
---
175+
176+
## License
177+
Apache-2.0. See [LICENSE](./LICENSE).
178+
179+
---
180+
181+
## Acknowledgements
182+
Built with PyTorch & the HF ecosystem; classic CV ops (Sobel/K-Means) via common libs. Thanks to collaborators and the community.

0 commit comments

Comments
 (0)