File size: 4,603 Bytes
01fdb75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import sys
sys.path.insert(0, "/data/sichengli/Code/PixelGen")

import torch
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import torchvision.transforms as transforms
import torchvision.transforms.functional as TF
import os, random

from src.models.transformer.JiT_medical import JiTMedical
from src.diffusion.flow_matching.sampling_medical import EulerSamplerMedical
from src.diffusion.flow_matching.scheduling import LinearScheduler
from src.diffusion.base.guidance import simple_guidance_fn

device = torch.device("cuda:0")

# Load model
ckpt_path = "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_B16/epoch=236-step=100000.ckpt"
ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
state_dict = ckpt["state_dict"]

model = JiTMedical(
    input_size=256, patch_size=16, in_channels=3,
    hidden_size=768, depth=12, num_heads=12, mlp_ratio=4.0,
    attn_drop=0.0, proj_drop=0.1, num_classes=1,
    use_bottleneck=True, bottleneck_dim=128,
    in_context_len=32, in_context_start=4, mask_in_channels=1
)
ema_state = {}
for k, v in state_dict.items():
    if k.startswith("ema_denoiser."):
        new_k = k.replace("ema_denoiser.", "").replace("_orig_mod.", "")
        ema_state[new_k] = v
model.load_state_dict(ema_state, strict=False)
model = model.to(device).eval().to(torch.float32)

sampler = EulerSamplerMedical(
    num_steps=50, guidance=2.0, timeshift=1.0,
    guidance_interval_min=0.1, guidance_interval_max=0.9,
    scheduler=LinearScheduler(), w_scheduler=LinearScheduler(),
    guidance_fn=simple_guidance_fn,
).to(device)

# Load 8 samples
data_root = "/data2/sichengli/Data/test/Segmentation/OCTA500"
img_dir = os.path.join(data_root, "images")
mask_dir = os.path.join(data_root, "masks")
all_files = sorted([f for f in os.listdir(img_dir) if f.endswith(".png") and not f.startswith("thumb")])
random.seed(456)
selected = random.sample(all_files, 8)

images_list, masks_list = [], []
for fname in selected:
    img = Image.open(os.path.join(img_dir, fname)).convert("L")
    img = TF.resize(img, (256, 256))
    images_list.append(TF.to_tensor(img).repeat(3, 1, 1))
    mask = Image.open(os.path.join(mask_dir, fname)).convert("L")
    mask = TF.resize(mask, (256, 256), interpolation=transforms.InterpolationMode.NEAREST)
    masks_list.append(TF.to_tensor(mask))

real_images = torch.stack(images_list)
masks_tensor = torch.stack(masks_list)

# Generate
print("Generating...")
with torch.no_grad():
    noise = torch.randn(8, 3, 256, 256, device=device)
    x_trajs, _ = sampler._impl_sampling(model, noise, None, None, mask=masks_tensor.to(device))
    generated = x_trajs[-1].clamp(-1, 1) * 0.5 + 0.5

# Create comparison: 8 rows x 3 columns (Mask | Generated | Real)
h, w = 256, 256
pad = 6
label_h = 40
n_rows = 8
n_cols = 3

canvas_w = n_cols * w + (n_cols + 1) * pad
canvas_h = n_rows * h + (n_rows + 1) * pad + label_h
canvas = np.ones((canvas_h, canvas_w, 3), dtype=np.uint8) * 30

# Add column labels
labels = ["Mask", "Generated", "Real"]
try:
    font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 24)
except Exception:
    font = ImageFont.load_default()

pil_canvas = Image.fromarray(canvas)
draw = ImageDraw.Draw(pil_canvas)
for col, label in enumerate(labels):
    x_pos = pad + col * (w + pad) + w // 2
    bbox = draw.textbbox((0, 0), label, font=font)
    text_w = bbox[2] - bbox[0]
    draw.text((x_pos - text_w // 2, 8), label, fill=(255, 255, 255), font=font)
canvas = np.array(pil_canvas)

# Colormap for mask classes
color_map = {
    0: (0, 0, 0),
    50: (255, 80, 80),
    100: (80, 255, 80),
    150: (80, 80, 255),
    200: (255, 255, 80),
    250: (255, 80, 255),
}

for row in range(n_rows):
    y = label_h + pad + row * (h + pad)

    # Mask - colorized
    m = masks_tensor[row, 0].numpy()
    m_uint8 = (m * 255).astype(np.uint8)
    m_colored = np.zeros((h, w, 3), dtype=np.uint8)
    for val, color in color_map.items():
        mask_region = np.abs(m_uint8.astype(int) - val) < 13
        m_colored[mask_region] = color
    canvas[y:y+h, pad:pad+w] = m_colored

    # Generated
    g = generated[row].cpu().permute(1, 2, 0).numpy()
    g = (g * 255).clip(0, 255).astype(np.uint8)
    canvas[y:y+h, 2*pad+w:2*pad+2*w] = g

    # Real
    r = real_images[row].permute(1, 2, 0).numpy()
    r = (r * 255).clip(0, 255).astype(np.uint8)
    canvas[y:y+h, 3*pad+2*w:3*pad+3*w] = r

out = "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_B16/val_samples/mask_control_final.png"
Image.fromarray(canvas).save(out)
print("Saved:", out, canvas.shape)