JustDelet commited on
Commit
d2246b7
·
verified ·
1 Parent(s): 57bbf59

Upload gen_images.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. gen_images.py +85 -0
gen_images.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ #
3
+ # NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ # and proprietary rights in and to this software, related documentation
5
+ # and any modifications thereto. Any use, reproduction, disclosure or
6
+ # distribution of this software and related documentation without an express
7
+ # license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+
9
+ """Generate images using pretrained network pickle."""
10
+
11
+ import os
12
+ import re
13
+ from typing import List, Optional, Union
14
+
15
+ import click
16
+ import dnnlib
17
+ import numpy as np
18
+ import PIL.Image
19
+ import torch
20
+
21
+ import legacy
22
+
23
+ #----------------------------------------------------------------------------
24
+
25
+ def parse_range(s: Union[str, List]) -> List[int]:
26
+ '''Parse a comma separated list of numbers or ranges and return a list of ints.
27
+
28
+ Example: '1,2,5-10' returns [1, 2, 5, 6, 7]
29
+ '''
30
+ if isinstance(s, list): return s
31
+ ranges = []
32
+ range_re = re.compile(r'^(\d+)-(\d+)$')
33
+ for p in s.split(','):
34
+ m = range_re.match(p)
35
+ if m:
36
+ ranges.extend(range(int(m.group(1)), int(m.group(2))+1))
37
+ else:
38
+ ranges.append(int(p))
39
+ return ranges
40
+
41
+ #----------------------------------------------------------------------------
42
+
43
+ @click.command()
44
+ @click.option('--network', 'network_pkl', help='Network pickle filename', required=True)
45
+ @click.option('--seeds', type=parse_range, help='List of random seeds (e.g., \'0,1,4-6\')', required=True)
46
+ @click.option('--class', 'class_idx', type=int, help='Class label (unconditional if not specified)')
47
+ @click.option('--outdir', help='Where to save the output images', type=str, required=True, metavar='DIR')
48
+ def generate_images(
49
+ network_pkl: str,
50
+ seeds: List[int],
51
+ outdir: str,
52
+ class_idx: Optional[int]
53
+ ):
54
+ print('Loading networks from "%s"...' % network_pkl)
55
+ device = torch.device('cuda')
56
+ with dnnlib.util.open_url(network_pkl) as f:
57
+ G = legacy.load_network_pkl(f)['G_ema'].to(device) # type: ignore
58
+
59
+ os.makedirs(outdir, exist_ok=True)
60
+
61
+ # Labels.
62
+ label = torch.zeros([1, G.c_dim], device=device)
63
+ if G.c_dim != 0:
64
+ if class_idx is None:
65
+ raise click.ClickException('Must specify class label with --class when using a conditional network')
66
+ label[:, class_idx] = 1
67
+ else:
68
+ if class_idx is not None:
69
+ print ('warn: --class=lbl ignored when running on an unconditional network')
70
+
71
+ # Generate images.
72
+ for seed_idx, seed in enumerate(seeds):
73
+ print('Generating image for seed %d (%d/%d) ...' % (seed, seed_idx, len(seeds)))
74
+ z = torch.from_numpy(np.random.RandomState(seed).randn(1, G.z_dim)).to(device)
75
+ img = G(z, label)
76
+ img = (img.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8)
77
+ PIL.Image.fromarray(img[0].cpu().numpy(), 'RGB').save(f'{outdir}/seed{seed:04d}.png')
78
+
79
+
80
+ #----------------------------------------------------------------------------
81
+
82
+ if __name__ == "__main__":
83
+ generate_images() # pylint: disable=no-value-for-parameter
84
+
85
+ #----------------------------------------------------------------------------