Created
August 13, 2017 16:00
-
-
Save pokotyamu/34e62550b59ed56069beee9046208f04 to your computer and use it in GitHub Desktop.
画像変換自由研究その1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PIL import Image | |
from PIL import ImageFilter | |
''' | |
実行に必要なパッケージをインストールする | |
$ pip install Pillow | |
''' | |
def put_on_wihte_space(image): | |
''' | |
600x600 に満たない画像をそれぞれの辺が最低でも600 になるように拡張する | |
''' | |
org_x, org_y = image.size | |
x = max(org_x, 600) | |
y = max(org_y, 600) | |
top_x = int((x - org_x) / 2) | |
top_y = int((y - org_y) / 2) | |
canvas = Image.new('RGB', (x, y), (255, 255, 255)) | |
canvas.paste(image, (top_x, top_y)) | |
return canvas | |
def compose_center(image, back_image): | |
''' | |
背景画像に対して指定した画像を中心に来るように重ね合わせる | |
''' | |
org_x, org_y = image.size | |
back_x, back_y = back_image.size | |
top_x = int((back_x - org_x) / 2) | |
top_y = int((back_y - org_y) / 2) | |
# 第3引数はアルファチャンネルがある場合のみ | |
image_info = image.split() | |
if len(image_info) == 3: | |
back_image.paste(image, (top_x, top_y)) | |
else: | |
back_image.paste(image, (top_x, top_y), image_info[3]) | |
return back_image | |
def expand_image(image): | |
''' | |
アスペクト比そのままで画像を拡大する | |
''' | |
x, y = aspect(image) | |
expaned_image = image.resize((x, y)) | |
return expaned_image | |
def aspect(image): | |
''' | |
短い方の辺が600になるときの縦横それぞれのサイズを返す | |
''' | |
x, y = image.size | |
ratio = 600 / min(x, y) | |
return int(x * ratio), int(y * ratio) | |
def black_back(): | |
return Image.new('RGB', (600, 600), (0, 0, 0)) | |
def white_back(): | |
return Image.new('RGB', (600, 600), (255, 255, 255)) | |
def blur_image(image): | |
''' | |
画像にブラーをかける | |
''' | |
return image.filter(ImageFilter.GaussianBlur(radius=20)) | |
''' | |
sample.png をブラーかけて背景にして画像サイズ変えてみる main | |
image = Image.open('./sample.png') | |
back = blur_image(expand_image(image)) | |
compose_center(image, back).show() | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment