-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
57 lines (48 loc) · 1.91 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
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 20 21:02:21 2018
@author: nicemo
"""
import os
from PIL import Image, ImageOps
import numpy as np
import scipy.misc
from six.moves import urllib
def download(download_link, file_name, expected_bytes):
""" Download the pretrained VGG-19 model if it's not already downloaded """
if os.path.exists(file_name):
print("VGG-19 pre-trained model is ready")
return
print("Downloading the VGG pre-trained model. This might take a while ...")
file_name, _ = urllib.request.urlretrieve(download_link, file_name)
file_stat = os.stat(file_name)
if file_stat.st_size == expected_bytes:
print('Successfully downloaded VGG-19 pre-trained model', file_name)
else:
raise Exception('File ' + file_name +
' might be corrupted. You should try downloading it with a browser.')
def safe_mkdir(path):
""" Create a directory if there isn't one already. """
try:
os.mkdir(path)
except OSError:
pass
def get_resized_image(img_path, width, height, save=True):
image = Image.open(img_path)
# PIL is column major so you have to swap the places of width and height
image = ImageOps.fit(image, (width, height), Image.ANTIALIAS)
if save:
image_dirs = img_path.split('/')
image_dirs[-1] = 'resized_' + image_dirs[-1]
out_path = '/'.join(image_dirs)
if not os.path.exists(out_path):
image.save(out_path)
image = np.asarray(image, np.float32)
return np.expand_dims(image, 0)
def generate_noise_image(content_image, width, height, noise_ratio=0.6):
noise_image = np.random.uniform(-20, 20, (1, height, width, 3)).astype(np.float32)
return noise_image * noise_ratio + content_image * (1 - noise_ratio)
def save_image(path, image):
image = image[0]
image = np.clip(image, 0, 255).astype('uint8')
scipy.misc.imsave(path, image)