-
Notifications
You must be signed in to change notification settings - Fork 435
/
utils.py
58 lines (50 loc) · 1.46 KB
/
utils.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
import tensorflow as tf
import random
def convert2int(image):
""" Transfrom from float tensor ([-1.,1.]) to int image ([0,255])
"""
return tf.image.convert_image_dtype((image+1.0)/2.0, tf.uint8)
def convert2float(image):
""" Transfrom from int image ([0,255]) to float tensor ([-1.,1.])
"""
image = tf.image.convert_image_dtype(image, dtype=tf.float32)
return (image/127.5) - 1.0
def batch_convert2int(images):
"""
Args:
images: 4D float tensor (batch_size, image_size, image_size, depth)
Returns:
4D int tensor
"""
return tf.map_fn(convert2int, images, dtype=tf.uint8)
def batch_convert2float(images):
"""
Args:
images: 4D int tensor (batch_size, image_size, image_size, depth)
Returns:
4D float tensor
"""
return tf.map_fn(convert2float, images, dtype=tf.float32)
class ImagePool:
""" History of generated images
Same logic as https://github.com/junyanz/CycleGAN/blob/master/util/image_pool.lua
"""
def __init__(self, pool_size):
self.pool_size = pool_size
self.images = []
def query(self, image):
if self.pool_size == 0:
return image
if len(self.images) < self.pool_size:
self.images.append(image)
return image
else:
p = random.random()
if p > 0.5:
# use old image
random_id = random.randrange(0, self.pool_size)
tmp = self.images[random_id].copy()
self.images[random_id] = image.copy()
return tmp
else:
return image