Views
No views yet
1import torch
2from torchvision.utils import save_image
3from huggingface_hub import hf_hub_download
4import sys, os
5
6# Download and load model
7model_file = hf_hub_download(
8 repo_id="hajar001/stylegan2-ffhq-128",
9 filename="style_gan.py"
10)
11sys.path.insert(0, os.path.dirname(model_file))
12from style_gan import StyleGAN
13
14model = StyleGAN.from_pretrained("hajar001/stylegan2-ffhq-128")
15device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
16model = model.to(device)
17model.eval()
18
19# Generate a single face
20with torch.no_grad():
21 z = torch.randn(1, 512, device=device)
22 images = model.generate(z, truncation_psi=0.7)
23
24# Denormalize from [-1, 1] to [0, 1]
25images = (images + 1) / 2
26images = torch.clamp(images, 0, 1)
27
28save_image(images, "generated_face.png")
29print("Generated face saved to generated_face.png")1# Generate 16 faces in a 4×4 grid
2with torch.no_grad():
3 z = torch.randn(16, 512, device=device)
4 images = model.generate(z, truncation_psi=0.7)
5
6images = (images + 1) / 2
7images = torch.clamp(images, 0, 1)
8
9save_image(images, "generated_faces_grid.png", nrow=4)
10print("Generated 16 faces")truncation_psi parameter controls the trade-off between quality and diversity:1.0: Maximum diversity, lower quality0.7: Balanced (recommended)0.5: Higher quality, less diversity1# High quality, less diverse
2images = model.generate(z, truncation_psi=0.5)
3
4# More diverse, slightly lower quality
5images = model.generate(z, truncation_psi=1.0)1# Generate two random latent codes
2z1 = torch.randn(1, 512, device=device)
3z2 = torch.randn(1, 512, device=device)
4
5# Mix styles (coarse features from z1, fine details from z2)
6with torch.no_grad():
7 w1 = model.mapping(z1)
8 w2 = model.mapping(z2)
9
10 # Create mixed w: first 4 layers from w1, rest from w2
11 w_mixed = torch.cat([
12 w1.unsqueeze(1).expand(-1, 4, -1),
13 w2.unsqueeze(1).expand(-1, 8, -1)
14 ], dim=1)
15
16 mixed_image = model.synthesis(w_mixed)
17
18mixed_image = (mixed_image + 1) / 2
19save_image(mixed_image, "style_mixed.png")1@article{karras2018stylebased,
2 title={A Style-Based Generator Architecture for Generative Adversarial Networks},
3 author={Karras, Tero and Laine, Samuli and Aila, Timo},
4 journal={arXiv preprint arXiv:1812.04948},
5 year={2018}
6}
7
8@article{karras2019stylegan2,
9 title={Analyzing and Improving the Image Quality of StyleGAN},
10 author={Karras, Tero and Laine, Samuli and Aittala, Miika and Hellsten, Janne and Lehtinen, Jaakko and Aila, Timo},
11 journal={arXiv preprint arXiv:1912.04958},
12 year={2019}
13}