python填充图像为方形

使用Python将图像填充为正方形
该代码段展示了一个Python脚本,它利用PIL库将任意尺寸的图像转换为正方形。输入图片的路径作为命令行参数,脚本会创建一个背景为白色的正方形图像,并将原始图像居中粘贴进去,最后保存结果为'xx.jpg'。

使用空白将图像填充为正方形

import sys
from PIL import Image

inp = str(sys.argv[1])
im = Image.open(inp)
x,y = im.size
size=max(x,y)
img=Image.new('RGBA', (size, size), (255,255,255,0))
img.paste(im, ((size - x) / 2, (size - y) / 2))
img.save('xx.jpg')

### 使用Python进行图片批量处理并将其转换为正方形 为了将多张非正方图像批量处理成正方形,可以基于给定的单张图片处理逻辑扩展到多个文件。此过程涉及遍历指定目录中的所有图片文件,并应用相同的填充和调整大小操作。 #### 扩展后的代码示例: ```python from PIL import Image import os def process_image_to_square(image_path, output_size=224): """ 将单个图片处理为正方形。 参数: image_path (str): 输入图片路径。 output_size (int): 输出图片的目标尺寸,默认为224x224像素。 返回: processed_image: 处理完成后的PIL.Image对象。 """ with Image.open(image_path) as img: img = img.convert('RGB') width, height = img.size # 创建灰色背景作为底板 side_length = max(width, height) background_color = (127, 127, 127) square_background = Image.new('RGB', (side_length, side_length), background_color) offset_x = abs(width - height) // 2 if width < height else 0 offset_y = abs(height - width) // 2 if height < width else 0 position = (offset_x, offset_y) # 把原图粘贴到底板中心位置 square_background.paste(img, position) # 调整至目标尺寸 final_img = square_background.resize((output_size, output_size)) return final_img def batch_process_images(input_folder, output_folder, target_size=224): """ 对输入文件夹内的所有支持格式的图片执行批量化处理, 并保存结果到输出文件夹中。 参数: input_folder (str): 存储待处理图片的源文件夹路径。 output_folder (str): 用于存储已处理图片的目的地文件夹路径。 target_size (int): 预期输出图片的高度/宽度,默认值为224px。 """ supported_formats = ['.jpg', '.jpeg', '.png'] try: os.makedirs(output_folder, exist_ok=True) for filename in os.listdir(input_folder): file_extension = os.path.splitext(filename)[1].lower() if file_extension not in supported_formats: continue full_input_path = os.path.join(input_folder, filename) result_image = process_image_to_square(full_input_path, target_size) new_filename = f"{os.path.splitext(filename)[0]}_processed{file_extension}" full_output_path = os.path.join(output_folder, new_filename) result_image.save(full_output_path) print(f"Processed and saved {new_filename}") except Exception as e: raise RuntimeError(f"Error during processing images: {e}") ``` 上述脚本定义了两个函数:`process_image_to_square()`负责单独处理一张图片;而`batch_process_images()`则是用来迭代整个文件夹的内容并对每张符合条件的图片调用前者来完成实际工作[^1]。 通过这种方式,不仅可以一次性处理大量不同比例的照片,还能确保最终得到统一规格的结果集。此外,在遇到不兼容类型的文件时也会自动跳过它们而不影响整体流程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值