forked from CompVis/stable-diffusion
-
Notifications
You must be signed in to change notification settings - Fork 16
/
inpaint_inference.py
164 lines (121 loc) · 5.23 KB
/
inpaint_inference.py
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import argparse, os, glob
from omegaconf import OmegaConf
from PIL import Image
from tqdm import tqdm
import numpy as np
import torch
# CHANGE WITH YOUR PATH
from main_inpainting import instantiate_from_config
from ldm.models.diffusion.ddim import DDIMSampler
from inpaint_utils import seed_everything
from inpaint_utils import make_batch,plot_row_original_mask_output
from contextlib import suppress
seed_everything(42)
# RUN SCRIPT
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Stable Diffusion Inpainting")
parser.add_argument(
"--indir",
type=str,
nargs="?",
help="dir containing image-mask pairs (`example.png` and `example_mask.png`)",
required=True
)
parser.add_argument(
"--outdir",
type=str,
nargs="?",
help="dir to write results to",
required=True
)
parser.add_argument(
"--prefix",
type=str,
default="",
help="path of weights to load",
required=True
)
parser.add_argument(
"--ckpt",
type=str,
help="path of weights to load",
required=True
)
parser.add_argument(
"--yaml_profile",
type=str,
help="yaml file describing the model to initialize",
required=True
)
parser.add_argument(
"--resize",
type=int,
default = 512,
help="resize to ",
)
parser.add_argument(
"--device",
type=str,
default="cpu",
help="specify the device for inference (cpu, cuda, cuda:x)",
)
parser.add_argument(
"--steps",
type=int,
default=50,
help="number of ddim sampling steps",
)
parser.add_argument(
"--ema",
action='store_true',
help="use ema weights",
)
opt = parser.parse_args()
masks = sorted(glob.glob(os.path.join(opt.indir, "*_mask.*")))
images = [x.replace("_mask.png", ".png") for x in masks]
print(f"Found {len(masks)} inputs.")
config = OmegaConf.load(opt.yaml_profile)
model = instantiate_from_config(config.model)
model.load_state_dict(torch.load(opt.ckpt)["state_dict"],
strict=False)
print("Loading modeling from %s" % opt.ckpt)
device = torch.device(opt.device) if torch.cuda.is_available() and opt.device is not "cpu" else torch.device("cpu")
model = model.to(device)
sampler = DDIMSampler(model)
os.makedirs(opt.outdir, exist_ok=True)
scope = model.ema_scope if opt.ema else suppress
ema_prefix = "EMA" if opt.ema else "NOT_EMA"
with torch.no_grad():
with scope("Sampling"):
for image, mask in tqdm(zip(images, masks)):
outpath = os.path.join(opt.outdir, "%s_%s_%s_%s.png" % (os.path.split(image)[1].split(".")[0], opt.prefix, ema_prefix, os.path.basename(opt.ckpt)))
batch = make_batch(image, mask, device=device, resize_to=opt.resize)
c_masked = model.cond_stage_model.encode(batch["masked_image"])
cc_mask = torch.nn.functional.interpolate(batch["mask"],
size=c_masked.shape[-2:])
c = torch.cat((c_masked,cc_mask), dim=1)
shape = (3,) + c_masked.shape[2:] # same
samples_ddim, _ = sampler.sample(S=opt.steps,
conditioning=c,
batch_size=c.shape[0],
shape=shape,
verbose=False)
x_samples_ddim = model.decode_first_stage(samples_ddim)
image = torch.clamp((batch["image"]+1.0)/2.0,
min=0.0, max=1.0)
mask = torch.clamp((batch["mask"]+1.0)/2.0,
min=0.0, max=1.0)
masked_image = torch.clamp((batch["masked_image"]+1.0)/2.0,
min=0.0, max=1.0)
predicted_image = torch.clamp((x_samples_ddim+1.0)/2.0,
min=0.0, max=1.0)
inpainted = (1-mask)*image+mask*predicted_image
inpainted = inpainted.cpu().numpy().transpose(0,2,3,1)[0]*255
predicted_image = predicted_image.cpu().numpy().transpose(0,2,3,1)[0]*255
print("Save in %s" % outpath)
mask = mask.cpu().numpy().transpose(0,2,3,1)[0]*255
image = image.cpu().numpy().transpose(0,2,3,1)[0]*255
masked_image = masked_image.cpu().numpy().transpose(0,2,3,1)[0]*255
# image_to_print = plot_row_original_mask_output([{"masked_image":masked_image, "image":image, "predicted_image":predicted_image}], image_size = 512)
# Image.fromarray(image_to_print.astype(np.uint8)).save(outpath)
Image.fromarray(predicted_image.astype(np.uint8)).save(outpath)