11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python Pillowを使って写真を中心から正方形にトリミングする

Last updated at Posted at 2018-04-24

やりたいこと

写真を一括で中心から正方形にトリミングする。

画像処理ライブラリPillowのインストール

pipでインストール

$ pip install Pillow

トリミング

下記のディレクトリ構成でimgディレクトリ内のjpg画像をトリミングしてtrimedディレクトリに保存する。

.
├── img
├── trimmed
trim.py

ソースコード

from PIL import Image
from pathlib import Path

# 元画像が入ったディレクトリ
p = Path('img/')
src_img_list = list(p.glob('*.jpg'))

# トリミングのサイズ(ピクセル)
new_size = 400

for i, src_img in enumerate(src_img_list):

    # 画像読み込み
    img = Image.open(src_img)

    # 中心座標を計算
    center_x = int(img.width / 2)
    center_y = int(img.height / 2)

    # トリミング
    img_crop = img.crop((center_x - new_size / 2, center_y - new_size / 2, center_x + new_size / 2, center_y + new_size / 2))

    # トリミングした画像を保存
    img_crop.save('trimmed/photo' + str(i) + '.jpg', 'JPEG', quality=100, optimize=True)

元画像
214hariIMGL9956_TP_V4.jpg

加工後
photo2.jpg

11
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?