LoginSignup
40
45

More than 5 years have passed since last update.

Python - アンチエイリアスで写真をキレイに縮小

Last updated at Posted at 2015-11-19

アンチエイリアスを掛けると写真縮小時のジャギジャギが軽減します。フォルダ内の写真ファイルをアスペクト比(縦横比率)を保ったまま一括で縮小してアンチエイリアスを掛け保存するPythonコードです。

アンチエリアスあり/なし比較

4000pxくらいの写真を300pxに縮小して比較しました。AA有りの鳥画像は地面の小さな砂が、地面と色が一体化して見えにくくなっています。

スクリーンショット 2015-11-19 21.03.02.png
スクリーンショット 2015-11-19 21.03.06.png

インストール

# PILのインストール
pip install PIL --allow-external PIL --allow-unverified PIL

拡大と縮小のコード

macのpython2.7環境でのみ動作確認済み

resize.py

# -*- coding: utf-8 -*-
import commands
import Image
import re

# 縮小する際の画像の高さピクセル
PHOTO_HEIGHT = 300

# 画像があるフォルダのフルパス
BASE_DIR = "/Users/XXXXX/Desktop/Photos"

# 画像の正規表現名
PHOTO_REGEX = r"P.*.[jpg|JPG]"

# リサイズ後の画像の接頭語
PHOTO_RESIZE_PREFIX = "r_"


def main():
    # 画像フルパスを取得
    _cmd = "cd {} && ls".format(BASE_DIR)
    l = commands.getoutput(_cmd)
    l = l.split("\n")
    l = [_l for _l in l if re.match(PHOTO_REGEX, _l)]

    # 出力用のフォルダを生成
    commands.getoutput("mkdir {}/output".format(BASE_DIR))

    # 既存ファイルを readモードで読み込み
    for _l in l:
        before_path = '{}/{}'.format(BASE_DIR, _l)
        filename = '{}{}'.format(PHOTO_RESIZE_PREFIX, _l)
        after_path = '{}/output/{}'.format(BASE_DIR, filename)
        resize(before_path, after_path, filename=_l)  # 縮小


def resize(before, after, height=PHOTO_HEIGHT, filename="", aa_enable=True):
    """
    画像をリサイズする
    :param str before: 元画像ファイルパス
    :param str after: リサイズ後の画像ファイルパス
    :param int height: リサイズ後の画像の高さ
    :param bool aa_enable: アンチエイリアスを有効にするか
    :return:
    """
    # 画像をreadonlyで開く
    img = Image.open(before, 'r')
    # リサイズ後の画像ピクセルを計算
    before_x, before_y = img.size[0], img.size[1]
    x = int(round(float(height / float(before_y) * float(before_x))))
    y = height
    resize_img = img
    if aa_enable:
        # アンチエイリアスありで縮小
        resize_img.thumbnail((x, y), Image.ANTIALIAS)
    else:
        # アンチエイリアスなしで縮小
        resize_img = resize_img.resize((x, y))

    # リサイズ後の画像を保存
    resize_img.save(after, 'jpeg', quality=100)
    print "RESIZED!:{}[{}x{}] --> {}x{}".format(filename, before_x, before_y, x, y)

# 実行
main()

実行結果
>>> python resize.py
RESIZED!:P1040673.jpg[4592x3448] --> 400x300
RESIZED!:P1050388.JPG[4592x3448] --> 400x300
RESIZED!:P1050389.JPG[4592x3448] --> 400x300
RESIZED!:P1050390.JPG[4592x3448] --> 400x300
RESIZED!:P1050391.JPG[4592x3448] --> 400x300
RESIZED!:P1050392.JPG[4592x3448] --> 400x300
RESIZED!:P1050393.JPG[4592x3448] --> 400x300
RESIZED!:P1050394.JPG[4592x3448] --> 400x300
40
45
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
40
45