Unconditional Image Generation
PyTorch
huggan
gan
geninhu commited on
Commit
f6b8ee7
1 Parent(s): eaed945

Upload utils.py

Browse files
Files changed (1) hide show
  1. utils.py +76 -0
utils.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from enum import Enum
4
+
5
+ import base64
6
+ import json
7
+ from io import BytesIO
8
+ from PIL import Image
9
+ import requests
10
+ import re
11
+
12
+ class ImageType(Enum):
13
+ REAL_UP_L = 0
14
+ REAL_UP_R = 1
15
+ REAL_DOWN_R = 2
16
+ REAL_DOWN_L = 3
17
+ FAKE = 4
18
+
19
+
20
+ def crop_image_part(image: torch.Tensor,
21
+ part: ImageType) -> torch.Tensor:
22
+ size = image.shape[2] // 2
23
+
24
+ if part == ImageType.REAL_UP_L:
25
+ return image[:, :, :size, :size]
26
+
27
+ elif part == ImageType.REAL_UP_R:
28
+ return image[:, :, :size, size:]
29
+
30
+ elif part == ImageType.REAL_DOWN_L:
31
+ return image[:, :, size:, :size]
32
+
33
+ elif part == ImageType.REAL_DOWN_R:
34
+ return image[:, :, size:, size:]
35
+
36
+ else:
37
+ raise ValueError('invalid part')
38
+
39
+
40
+ def init_weights(module: nn.Module):
41
+ if isinstance(module, nn.Conv2d):
42
+ torch.nn.init.normal_(module.weight, 0.0, 0.02)
43
+
44
+ if isinstance(module, nn.BatchNorm2d):
45
+ torch.nn.init.normal_(module.weight, 1.0, 0.02)
46
+ module.bias.data.fill_(0)
47
+
48
+ def load_image_from_local(image_path, image_resize=None):
49
+ image = Image.open(image_path)
50
+
51
+ if isinstance(image_resize, tuple):
52
+ image = image.resize(image_resize)
53
+ return image
54
+
55
+ def load_image_from_url(image_url, rgba_mode=False, image_resize=None, default_image=None):
56
+ try:
57
+ image = Image.open(requests.get(image_url, stream=True).raw)
58
+
59
+ if rgba_mode:
60
+ image = image.convert("RGBA")
61
+
62
+ if isinstance(image_resize, tuple):
63
+ image = image.resize(image_resize)
64
+
65
+ except Exception as e:
66
+ image = None
67
+ if default_image:
68
+ image = load_image_from_local(default_image, image_resize=image_resize)
69
+
70
+ return image
71
+
72
+ def image_to_base64(image_array):
73
+ buffered = BytesIO()
74
+ image_array.save(buffered, format="PNG")
75
+ image_b64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
76
+ return f"data:image/png;base64, {image_b64}"