Python将图片批量裁剪为指定大小256*1024

import os

from PIL import Image, ImageOps


def modify_image(image_path):
    # 打开图片并转化为灰度图
    image = Image.open(image_path).convert('L')

    # 计算需要添加的左右和上下边框的宽度
    w, h = image.size
    left_right_padding = (1024 - w) // 2
    top_bottom_padding = (256 - h) // 2

    # 如果图像宽度小于 1024,进行左右对称的方式扩充
    if w < 1024:
        # 左边边框的大小
        left = left_right_padding
        # 右边边框的大小
        right = 1024 - w - left
        # 上下边框大小
        top = top_bottom_padding
        bottom = 256 - h - top
        # 扩充图像
        image = ImageOps.expand(image, (left, top, right, bottom), fill=128)#fil=128代表填充区域会灰度值,可自行设定。(黑色为0)

    # 如果图像宽度大于 1024,进行中心裁剪
    elif w > 1024:
        # 裁剪框的左上角和右下角坐标
        left = (w - 1024) // 2
        right = left + 1024
        top = (h - 256) // 2
        bottom = top + 256
        # 进行裁剪
        image = image.crop((left, top, right, bottom))

    # 如果图像宽度等于 1024,进行上下对称的方式扩充
    else:
        # 左右边框大小
        left = left_right_padding
        right = left_right_padding
        # 上下边框大小
        top = top_bottom_padding
        bottom = top_bottom_padding
        # 扩充图像
        image = ImageOps.expand(image, (left, top, right, bottom), fill=128) #fil=128代表填充区域会灰度值。

    return image


def batch_modify_images(input_dir, output_dir):
    for file_name in os.listdir(input_dir):
        if file_name.endswith('.bmp'):
            # 调用修改图片函数进行处理
            image_path = os.path.join(input_dir, file_name)
            modified_image = modify_image(image_path)

            # 保存处理后的图片到指定目录
            output_file_name = '' + file_name
            output_path = os.path.join(output_dir, output_file_name)
            modified_image.save(output_path)


input_dir = './1'
output_dir = './2'
batch_modify_images(input_dir, output_dir)


 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Anger、破晓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值