Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added SSIM support, quality of life improvements in invert.py #28

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,14 @@ Please download the pre-trained models from the following links and save them to
```bash
MODEL_NAME='styleganinv_ffhq256'
IMAGE_LIST='examples/test.list'
python invert.py $MODEL_NAME $IMAGE_LIST
python invert.py --model_name $MODEL_NAME --image_list $IMAGE_LIST
```

```bash
MODEL_NAME='styleganinv_ffhq256'
IMAGE_DIR='examples/images/'

python invert.py --model_name $MODEL_NAME --image_dir $IMAGE_DIR
```

**NOTE:** We find that 100 iterations are good enough for inverting an image, which takes about 8s (on P40). But users can always use more iterations (much slower) for a more precise reconstruction.
Expand All @@ -47,7 +54,7 @@ python invert.py $MODEL_NAME $IMAGE_LIST
MODEL_NAME='styleganinv_ffhq256'
TARGET_LIST='examples/target.list'
CONTEXT_LIST='examples/context.list'
python diffuse.py $MODEL_NAME $TARGET_LIST $CONTEXT_LIST
python diffuse.py --model_name $MODEL_NAME --target_list $TARGET_LIST --context_list $CONTEXT_LIST
```

NOTE: The diffusion process is highly similar to image inversion. The main difference is that only the target patch is used to compute loss for **masked** optimization.
Expand All @@ -57,15 +64,15 @@ NOTE: The diffusion process is highly similar to image inversion. The main diffe
```bash
SRC_DIR='results/inversion/test'
DST_DIR='results/inversion/test'
python interpolate.py $MODEL_NAME $SRC_DIR $DST_DIR
python interpolate.py --model_name $MODEL_NAME --src_dir $SRC_DIR --dst_dir $DST_DIR
```

### Manipulation

```bash
IMAGE_DIR='results/inversion/test'
BOUNDARY='boundaries/expression.npy'
python manipulate.py $MODEL_NAME $IMAGE_DIR $BOUNDARY
python manipulate.py --model_name $MODEL_NAME --image_dir $IMAGE_DIR --boundary_path $BOUNDARY
```

**NOTE:** Boundaries are obtained using [InterFaceGAN](https://github.com/genforce/interfacegan).
Expand All @@ -75,7 +82,7 @@ python manipulate.py $MODEL_NAME $IMAGE_DIR $BOUNDARY
```bash
STYLE_DIR='results/inversion/test'
CONTENT_DIR='results/inversion/test'
python mix_style.py $MODEL_NAME $STYLE_DIR $CONTENT_DIR
python mix_style.py --model_name $MODEL_NAME --style_dir $STYLE_DIR --content_dir $CONTENT_DIR
```

## BibTeX
Expand Down
6 changes: 3 additions & 3 deletions diffuse.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@
def parse_args():
"""Parses arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('model_name', type=str, help='Name of the GAN model.')
parser.add_argument('target_list', type=str,
parser.add_argument('--model_name', type=str, help='Name of the GAN model.')
parser.add_argument('--target_list', type=str,
help='List of target images to diffuse from.')
parser.add_argument('context_list', type=str,
parser.add_argument('--context_list', type=str,
help='List of context images to diffuse to.')
parser.add_argument('-o', '--output_dir', type=str, default='',
help='Directory to save the results. If not specified, '
Expand Down
2 changes: 1 addition & 1 deletion examples/test.list
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ examples/000015.png
examples/000016.png
examples/000017.png
examples/000018.png
examples/000019.png
examples/000019.png
6 changes: 3 additions & 3 deletions interpolate.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@
def parse_args():
"""Parses arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('model_name', type=str, help='Name of the GAN model.')
parser.add_argument('src_dir', type=str,
parser.add_argument('--model_name', type=str, help='Name of the GAN model.')
parser.add_argument('--src_dir', type=str,
help='Source directory, which includes original images, '
'inverted codes, and image list.')
parser.add_argument('dst_dir', type=str,
parser.add_argument('--dst_dir', type=str,
help='Target directory, which includes original images, '
'inverted codes, and image list.')
parser.add_argument('-o', '--output_dir', type=str, default='',
Expand Down
61 changes: 51 additions & 10 deletions invert.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,12 @@
def parse_args():
"""Parses arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('model_name', type=str, help='Name of the GAN model.')
parser.add_argument('image_list', type=str,
parser.add_argument('--model_name', type=str, help='Name of the GAN model.')
parser.add_argument('--image_list', type=str, default = '',
help='List of images to invert.')

parser.add_argument('--test_dir', type=str, default = '',
help='directory of images to invert.')
parser.add_argument('-o', '--output_dir', type=str, default='',
help='Directory to save the results. If not specified, '
'`./results/inversion/${IMAGE_LIST}` '
Expand All @@ -38,6 +41,11 @@ def parse_args():
parser.add_argument('--loss_weight_feat', type=float, default=5e-5,
help='The perceptual loss scale for optimization. '
'(default: 5e-5)')

parser.add_argument('--loss_weight_ssim', type=float, default=1.0,
help='The perceptual loss scale for optimization. '
'(default: 1)')

parser.add_argument('--loss_weight_enc', type=float, default=2.0,
help='The encoder loss scale for optimization.'
'(default: 2.0)')
Expand All @@ -52,9 +60,24 @@ def main():
"""Main function."""
args = parse_args()
os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu_id
assert os.path.exists(args.image_list)
image_list_name = os.path.splitext(os.path.basename(args.image_list))[0]
if args.image_list != '' and args.test_dir == '':
assert os.path.exists(args.image_list)
image_list_name = os.path.splitext(os.path.basename(args.image_list))[0]
elif args.test_dir != '' and args.image_list == '' :
assert os.path.exists(args.test_dir)
image_list_name = os.path.splitext(os.path.basename(args.test_dir))[0]
else:
raise Exception("Use either --image_list or --test_dir. Using both arguments at the same time not supported.")


MODEL_DIR = os.path.join('models', 'pretrain')
os.makedirs(MODEL_DIR, exist_ok=True)
if(all(x not in os.listdir(MODEL_DIR) for x in ["styleganinv_ffhq256_encoder.pth" , "styleganinv_ffhq256_generator.pth" , "vgg16.pth"])):
raise Exception("styleganinv_ffhq256_encoder.pth , styleganinv_ffhq256_generator.pth and vgg16.pth missing")

output_dir = args.output_dir or f'results/inversion/{image_list_name}'
if not os.path.exists(output_dir):
os.makedirs(output_dir)
logger = setup_logger(output_dir, 'inversion.log', 'inversion_logger')

logger.info(f'Loading model.')
Expand All @@ -65,15 +88,27 @@ def main():
reconstruction_loss_weight=1.0,
perceptual_loss_weight=args.loss_weight_feat,
regularization_loss_weight=args.loss_weight_enc,
loss_weight_ssim = args.loss_weight_ssim,
logger=logger)
image_size = inverter.G.resolution

# Load image list.
logger.info(f'Loading image list.')
image_list = []
with open(args.image_list, 'r') as f:
for line in f:
image_list.append(line.strip())
if args.image_list !='':

with open(args.image_list, 'r') as f:
for line in f:
image_list.append(line.strip())

if args.test_dir !='':
for root, dirs, files in os.walk(args.test_dir):
for file in files:
image_list.append(file)


#print(len(image_list))
logger.info(f'loaded {len(image_list)} images')

# Initialize visualizer.
save_interval = args.num_iterations // args.num_results
Expand All @@ -90,10 +125,15 @@ def main():
logger.info(f'Start inversion.')
latent_codes = []
for img_idx in tqdm(range(len(image_list)), leave=False):
image_path = image_list[img_idx]
image_name = os.path.splitext(os.path.basename(image_path))[0]
if args.image_list !='':
image_path = image_list[img_idx]
image_name = os.path.splitext(os.path.basename(image_path))[0]
elif args.test_dir !='':
image_path = os.path.join( args.test_dir, image_list[img_idx])
image_name = os.path.splitext(os.path.basename(image_list[img_idx]))[0]

image = resize_image(load_image(image_path), (image_size, image_size))
code, viz_results = inverter.easy_invert(image, num_viz=args.num_results)
code, viz_results , ssim_loss = inverter.easy_invert(np.array(image), num_viz=args.num_results)
latent_codes.append(code)
save_image(f'{output_dir}/{image_name}_ori.png', image)
save_image(f'{output_dir}/{image_name}_enc.png', viz_results[1])
Expand All @@ -103,6 +143,7 @@ def main():
for viz_idx, viz_img in enumerate(viz_results[1:]):
visualizer.set_cell(img_idx, viz_idx + 2, image=viz_img)


# Save results.
os.system(f'cp {args.image_list} {output_dir}/image_list.txt')
np.save(f'{output_dir}/inverted_codes.npy',
Expand Down
6 changes: 3 additions & 3 deletions manipulate.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@
def parse_args():
"""Parses arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('model_name', type=str, help='Name of the GAN model.')
parser.add_argument('image_dir', type=str,
parser.add_argument('--model_name', type=str, help='Name of the GAN model.')
parser.add_argument('--image_dir', type=str,
help='Image directory, which includes original images, '
'inverted codes, and image list.')
parser.add_argument('boundary_path', type=str,
parser.add_argument('--boundary_path', type=str,
help='Path to the boundary for semantic manipulation.')
parser.add_argument('-o', '--output_dir', type=str, default='',
help='Directory to save the results. If not specified, '
Expand Down
6 changes: 3 additions & 3 deletions mix_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@
def parse_args():
"""Parses arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('model_name', type=str, help='Name of the GAN model.')
parser.add_argument('style_dir', type=str,
parser.add_argument('--model_name', type=str, help='Name of the GAN model.')
parser.add_argument('--style_dir', type=str,
help='Style directory, which includes original images, '
'inverted codes, and image list.')
parser.add_argument('content_dir', type=str,
parser.add_argument('--content_dir', type=str,
help='Content directory, which includes original images, '
'inverted codes, and image list.')
parser.add_argument('-o', '--output_dir', type=str, default='',
Expand Down
Loading