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)
coze
应用 上午 10:53
好的,以下是实现该功能的 Python 脚本。它将遍历指定的文件夹,将每个图片调整为 4:3 的比例,原始图片内容居中,并在需要的时候填充白色背景。
python
import os
from PIL import Image
def resize_images_to_43_aspect_ratio(directory):
for filename in os.listdir(directory):
if filename.endswith(".jpg") or filename.endswith(".png"):
filepath = os.path.join(directory, filename)
img = Image.open(filepath)
# 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(filepath)
# Use function on a directory
resize_images_to_43_aspect_ratio("/path/to/your/directory")
请注意将 "/path/to/your/directory" 替换为你实际的文件夹路径。这个脚本默认会覆盖原来的图片,如果你希望保留原图,可以在 new_img.save(filepath) 这一行修改文件路径来保存为新的文件。例如 new_img.save(os.path.join(directory, "resized_" + filename)),这样会在原文件名前添加 "resized_" 并保存为新的文件。
coze
应用 中午 11:48
当然,以下是一个实现的例子:
python
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])
# 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)
在此函数中,通过将图片转换为 NumPy 数组,我们可以很方便地获取所有非白色像素的坐标,并据此来裁剪图像。
请注意,这份代码假定白色像素是空白区域。如果你的空白区域的颜色不是白色,或者图像背景中包含其他颜色的像素,那么你可能需要进行一些额外的颜色检查或预处理步骤。
还要注意,根据图片的颜色模式,可能需要对 img_data != 255 部分进行调整。这是因为对于 RGB 图像,需要比较的将是一个 (R, G, B) 元素的元组,而不仅仅是一个单一的像素值。
我
下午 2:18
用这个替换掉上面的remove_whitespace
coze
应用 下午 2:19
好的,这里是使用新的 crop_image 函数替换掉 remove_whitespace 函数后的处理流程示例:
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])
# 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)
def process_images(folder):
for filename in os.listdir(folder):
if filename.endswith(".jpg"):
image_path = os.path.join(folder, filename)
print(f"Processing image at {image_path}")
crop_image(image_path)
我
下午 2:35
import os
from PIL import Image
def resize_images_to_43_aspect_ratio(directory):
for filename in os.listdir(directory):
if filename.endswith(".jpg") or filename.endswith(".png"):
filepath = os.path.join(directory, filename)
img = Image.open(filepath)
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(filepath)
# Use function on a directory
resize_images_to_43_aspect_ratio("/path/to/your/directory") 把这个把图片转换成4:3比例的代码加进去,处理图片的时候,先把多余的空白删掉,然后再转换成4:3
coze
应用 下午 2:36
当然,我可以帮你整合这两段代码,首先删除多余的空白,然后再将图像转换成4:3的比例。下面就是整合后的代码:
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])
# 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"):
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 = "/path/to/your/directory"
# 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)
这将确保我们在提取图像的非白色区域时,保留了至少10个像素的白色边框。我们使用 max 和 min 函数来确保裁剪区域始终在图像的边界内,防止出现尝试裁剪超出图像边界的情况。
我
下午 2:44
这个代码能处理webp的图片么
coze
应用 下午 2:44
PIL库支持读取和保存webp格式的图片,所以这段代码可以处理webp格式的图片。只需要稍作修改,让代码也对后缀为 ".webp" 的文件进行处理即可。这是修改后的代码:
python
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)