Created
March 21, 2024 08:20
-
-
Save kuloud/732199359b6f8199c625dc9550d1e806 to your computer and use it in GitHub Desktop.
图片批处理拓展指定大小并移除白色背景
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| from PIL import Image | |
| def process_image(input_path, output_path, target_width, target_height): | |
| # 打开图片 | |
| image = Image.open(input_path) | |
| # 获取图片原始尺寸 | |
| width, height = image.size | |
| # 计算缩放比例 | |
| scale = min(target_width / width, target_height / height) | |
| # 缩放图片 | |
| scaled_image = image.resize((int(width * scale), int(height * scale))) | |
| # 计算新的尺寸 | |
| new_width, new_height = scaled_image.size | |
| # 创建白色背景 | |
| background = Image.new('RGB', (target_width, target_height), (255, 255, 255)) | |
| # 将缩放后的图片转换为 RGBA 模式 | |
| scaled_image = scaled_image.convert('RGBA') | |
| # 设定背景透明阈值 | |
| threshold = 254 | |
| # 遍历像素,将背景变为透明 | |
| for x in range(new_width): | |
| for y in range(new_height): | |
| r, g, b, a = scaled_image.getpixel((x, y)) | |
| if r > threshold and g > threshold and b > threshold: | |
| scaled_image.putpixel((x, y), (255, 255, 255, 0)) | |
| # 将缩放后的图片粘贴到白色背景上 | |
| background.paste(scaled_image, ((target_width - new_width) // 2, (target_height - new_height) // 2)) | |
| # 保存图片 | |
| background.save(output_path) | |
| input_dir = "./images" | |
| size = 1024 | |
| output_dir = f"./out_{size}" | |
| # 批量处理图片 | |
| for filename in os.listdir(input_dir): | |
| input_path = os.path.join(input_dir, filename) | |
| base_filename, _ = os.path.splitext(filename) | |
| output_path = os.path.join(output_dir, f"{base_filename}.png") | |
| process_image(input_path, output_path, target_width=size, target_height=size) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment