eightban's memo

残しておきたい記事をまとめてみました。このブログに書いてあるドキュメントやブログで配布しているファイルの使用によって発生するいかなる損害に対してもこのブログの管理者は責任を負いません。使用する場合は自己責任のもとに使用してください。

Python 画像

画像をリサイズした後余白を追加するPythonプログラム

更新日:

縦横の拡大縮小比率を同じにして大きさを変えた後 透明な余白を追加するプログラムです

コード

from PIL import Image, ImageOps
import numpy as np
import os

def resize_image(image, new_width, new_height):
    width_ratio = new_width / image.width
    height_ratio = new_height / image.height
    ratio = min(width_ratio, height_ratio)
    new_size = (int(image.width * ratio), int(image.height * ratio))
    resized_image = image.resize(new_size, Image.ANTIALIAS)
    new_image = Image.new("RGBA", (new_width, new_height), (0, 0, 0, 0))
    x = (new_width - new_size[0]) // 2
    y = (new_height - new_size[1]) // 2
    new_image.paste(resized_image, (x, y))
    return new_image

def add_padding(image,  target_aspect_ratio):
    original_width, original_height = image.size
    if original_width / original_height > target_aspect_ratio:
        new_height = original_width / target_aspect_ratio
        new_width = original_width
    else:
        new_width = original_height * target_aspect_ratio
        new_height = original_height
    new_image = Image.new("RGBA", (int(new_width), int(new_height)), (0, 0, 0, 0))
    x_offset = (int(new_width) - original_width) // 2
    y_offset = (int(new_height) - original_height) // 2
    new_image.paste(image, (x_offset, y_offset))
    return new_image
def batch_process_images(input_folder, output_folder,width,height):
    # 出力フォルダが存在しない場合は作成
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 入力フォルダ内の画像ファイルを一括で処理
    for filename in os.listdir(input_folder):
        if filename.endswith(('.jpg', '.jpeg', '.png', '.bmp', '.gif')):
            input_path = os.path.join(input_folder, filename)
            output_path = os.path.join(output_folder, filename)
            image = Image.open(input_path)
            image = resize_image(image,width,height)
            output_image = add_padding(image,width/height)
            output_image.save(output_path)

# 使用例:
input_folder = 'input_folder'
output_folder = 'output_folder'
output_f = 'output_folder'
output_folder = os.path.join(input_folder, output_f)
width = 512
height = 512
batch_process_images(input_folder, output_folder, width,height)

-Python, 画像

Copyright© eightban's memo , 2024 All Rights Reserved Powered by STINGER.