master
/ coding_here.ipynb

coding_here.ipynb @64b73acview markup · raw · history · blame

Notebook
In [10]:
import torch
#import torchvision.models as models
from torchvision.models.vgg import vgg16
vgg = vgg16(pretrained=False)
vgg.load_state_dict(torch.load('vgg16.pth'))
print(vgg)
print('ok')
VGG(
  (features): Sequential(
    (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU(inplace=True)
    (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (3): ReLU(inplace=True)
    (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (6): ReLU(inplace=True)
    (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (8): ReLU(inplace=True)
    (9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (11): ReLU(inplace=True)
    (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (13): ReLU(inplace=True)
    (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (15): ReLU(inplace=True)
    (16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (18): ReLU(inplace=True)
    (19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (20): ReLU(inplace=True)
    (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (22): ReLU(inplace=True)
    (23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (25): ReLU(inplace=True)
    (26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (27): ReLU(inplace=True)
    (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (29): ReLU(inplace=True)
    (30): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (avgpool): AdaptiveAvgPool2d(output_size=(7, 7))
  (classifier): Sequential(
    (0): Linear(in_features=25088, out_features=4096, bias=True)
    (1): ReLU(inplace=True)
    (2): Dropout(p=0.5, inplace=False)
    (3): Linear(in_features=4096, out_features=4096, bias=True)
    (4): ReLU(inplace=True)
    (5): Dropout(p=0.5, inplace=False)
    (6): Linear(in_features=4096, out_features=1000, bias=True)
  )
)
ok
In [3]:
import argparse
import torch
import matplotlib.pyplot as plt # plt 用于显示图片
from PIL import Image
from torch.autograd import Variable
from torchvision.transforms import ToTensor, ToPILImage
from model import Generator

UPSCALE_FACTOR=4
IMAGE_NAME ='BSD100_009.png'
MODEL_NAME = 'netG_epoch_4_100.pth'
model = Generator(UPSCALE_FACTOR).eval()
model.load_state_dict(torch.load('results/epochs/' + MODEL_NAME, map_location=lambda storage, loc: storage))

image = Image.open(IMAGE_NAME)
image = Variable(ToTensor()(image), volatile=True).unsqueeze(0)

out = model(image)
out_img = ToPILImage()(out[0].data.cpu())
plt.imshow(out_img)
plt.axis('off') # 不显示坐标轴
plt.show()
out_img.save('out_srf_' + str(UPSCALE_FACTOR) + '_' + IMAGE_NAME)
/home/jovyan/.virtualenvs/basenv/lib/python3.5/site-packages/ipykernel_launcher.py:16: UserWarning: volatile was removed and now has no effect. Use `with torch.no_grad():` instead.
  app.launch_new_instance()
In [5]:
import os
import sys
import time
import re
import base64
from io import BytesIO
from PIL import Image
def image_to_base64(img):
    global scale
    buffered = BytesIO()
    imgSize = img.size
    if scale > 1:
        resize_img = img.resize((int(imgSize[0]*scale), int(imgSize[1]*scale)))
    else:
        resize_img = img
    resize_img.save(buffered, format="JPEG")
    img_str = base64.b64encode(buffered.getvalue())
    return img_str.decode("utf-8")
In [14]:
import base64
from io import BytesIO

# pip3 install pillow
from PIL import Image

# 若img.save()报错 cannot write mode RGBA as JPEG
# 则img = Image.open(image_path).convert('RGB')
def image_to_base64(image_path):
    img = Image.open(image_path)
    output_buffer = BytesIO()
    img.save(output_buffer, format='JPEG')
    byte_data = output_buffer.getvalue()
    base64_str = base64.b64encode(byte_data)
    return base64_str
In [15]:
import re
import base64
from io import BytesIO

from PIL import Image


def base64_to_image(base64_str, image_path=None):
    base64_data = re.sub('^data:image/.+;base64,', '', base64_str)
    byte_data = base64.b64decode(base64_data)
    image_data = BytesIO(byte_data)
    img = Image.open(image_data)
    if image_path:
        img.save(image_path)
    return img
In [17]:
import matplotlib.pyplot as plt # plt 用于显示图片
img =  'BSD100_009.png'
img_str = image_to_base64(img)
#print(img_str)
out_img = base64_to_image(img_str,False)
plt.imshow(out_img)
plt.axis('off') # 不显示坐标轴
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-17-63d09351ee56> in <module>
      3 img_str = image_to_base64(img)
      4 #print(img_str)
----> 5 out_img = base64_to_image(img_str,False)
      6 plt.imshow(out_img)
      7 plt.axis('off') # 不显示坐标轴

<ipython-input-15-e2ea5d129f93> in base64_to_image(base64_str, grayscale)
     10     # print(base64_str)
     11     global scale
---> 12     base64_data = re.sub('^data:image/.+;base64,', '', base64_str)
     13     byte_data = base64.b64decode(base64_data)
     14     image_data = BytesIO(byte_data)

~/work/.localenv/lib/python3.5/re.py in sub(pattern, repl, string, count, flags)
    180     a callable, it's passed the match object and must return
    181     a replacement string to be used."""
--> 182     return _compile(pattern, flags).sub(repl, string, count)
    183 
    184 def subn(pattern, repl, string, count=0, flags=0):

TypeError: cannot use a string pattern on a bytes-like object
In [ ]:
5dd13c5024d57fa935c71de9?type=app

# Initialise Client object
client = Client(api_key='33799e1c5d6fa05fdd7dec3aa7aad868445d1c737edcf9c37fa89cb3b39cb2d9',
                project_id='5bf7c0491afd94074fb77d3c', user_ID='harvien',
                project_type='app', source_file_path='picmigration.py', 
                silent=True)

# Make run/train/predict command alias for further use
run = client.run
train = client.train
predict = client.predict

# Make controller alias for further use
controller = client.controller