Python批量把白底图片比例转换成4:3

查看 61|回复 3
作者:linjian648   
做电商可能用得到,今天我就有这个需求,然后找gpt帮我写了代码。比较简单,所有我会把跟gpt的聊天记录发在帖子后面,有兴趣可以看看。
流程就是,先检测图片的白边,然后把白边都删掉,留10个像素的白边,全删完了太难看。
然后检测图片比例,用白色像素来填充不够的区域,原来的图片居中。
[Python] 纯文本查看 复制代码import os
from PIL import Image
import numpy as np
def crop_image(image_path):
    img = Image.open(image_path)
    # Convert image to numpy array
    img_data = np.asarray(img)
    # Get the bounding box
    non_white_pixels = np.where(img_data != 255)
    min_y, max_y = np.min(non_white_pixels[0]), np.max(non_white_pixels[0])
    min_x, max_x = np.min(non_white_pixels[1]), np.max(non_white_pixels[1])
   
    # Adjust the bounding box to leave a 10 pixel border
    min_y = max(0, min_y - 10) # Ensure it's not less than 0
    min_x = max(0, min_x - 10) # Ensure it's not less than 0
    max_y = min(img_data.shape[0], max_y + 10) # Ensure it's not greater than the image height
    max_x = min(img_data.shape[1], max_x + 10) # Ensure it's not greater than the image width
    # Crop the image to this bounding box
    cropped_img = img.crop((min_x, min_y, max_x, max_y))
    # Save the cropped image
    cropped_img.save(image_path)
# original function to resize image to 4:3
def resize_image_to_43(image_path):
    img = Image.open(image_path)
    original_width, original_height = img.size
    target_aspect_ratio = 4 / 3
    # Calculate target size with same aspect ratio
    if original_width / original_height > target_aspect_ratio:
        # if image is wider than target aspect ratio, adjust height
        target_height = int(original_width / target_aspect_ratio)
        target_width = original_width
    else:
        # if image is taller than target aspect ratio, adjust width
        target_width = int(original_height * target_aspect_ratio)
        target_height = original_height
    # Create new image with white background
    new_img = Image.new("RGB", (target_width, target_height), "white")
    # calculate paste coordinates to center original image
    paste_x = (target_width - original_width) // 2
    paste_y = (target_height - original_height) // 2
    new_img.paste(img, (paste_x, paste_y))
    # Save new image overwriting the old one
    new_img.save(image_path)
# now we integrate them in process_images function
def process_images(folder):
    for filename in os.listdir(folder):
        if filename.endswith(".jpg") or filename.endswith(".png") or filename.endswith(".webp"):
            image_path = os.path.join(folder, filename)
            print(f"Processing image at {image_path}")
            crop_image(image_path)
            resize_image_to_43(image_path)
            
# replace this with your own directory
folder = "F:\Desktop\新建文件夹"
process_images(folder)
聊天记录:
"

图片, 函数

linjian648
OP
  

cropped_img.save(image_path, quality=99)
new_img.save(image_path, quality=99)
试了下,转出来的图片质量会下降,在两个保存的代码后面加上图片质量好很多
dsman   

ModuleNotFoundError: No module named 'PIL'
怎么破?
wj21   

怎么觉得这个与GPT的交流过程也挺费事的呢
您需要登录后才可以回帖 登录 | 立即注册

返回顶部