我正在编写一个图像处理脚本。
我从背景去除 API 返回的图像具有完美的颜色和质量。
但是一旦我裁剪,放在画布上并保存,颜色就不那么鲜艳了,而且质量也不那么好。
下面是我的裁剪和保存功能。
def crop_and_resize_sneaker(bg_removed_image_path, bounding_box, output_dir, image_name):
"""
Crops and resizes an image to fit a 1400 x 1000 canvas while maintaining quality.
Uses PIL to handle images with an emphasis on preserving the original quality,
especially during resizing and saving operations.
"""
try:
# Load the image with background removed
image = Image.open(bg_removed_image_path).convert('RGBA')
# Extract bounding box coordinates
x, y, w, h = bounding_box
# Crop the image based on the bounding box
cropped_image = image.crop((x, y, x + w, y + h))
# Define output dimensions
output_width, output_height = 1400, 1000
# Calculate new dimensions to maintain aspect ratio
aspect_ratio = w / h
if aspect_ratio > (output_width / output_height):
new_width = output_width
new_height = int(output_width / aspect_ratio)
else:
new_width = int(output_height * aspect_ratio)
new_height = output_height
# Resize the image using LANCZOS (high-quality)
resized_image = cropped_image.resize((new_width, new_height), Image.LANCZOS)
# Create a new image for the final output with a transparent background
final_image = Image.new('RGBA', (output_width, output_height), (0, 0, 0, 0))
# Calculate center positioning
start_x = (output_width - new_width) // 2
start_y = (output_height - new_height) // 2
# Paste the resized image onto the transparent canvas
final_image.paste(resized_image, (start_x, start_y), resized_image)
# Save the final image as PNG with maximum quality settings
final_img_path = os.path.join(output_dir, 'resized', f'{image_name}_sneaker_canvas.png')
final_image.save(final_img_path, 'PNG', quality=95) # Although 'quality' has no effect on PNGs, provided for completeness
return final_img_path
except Exception as e:
logging.error(f"Error in cropping and resizing sneaker: {e}")
return None
如何确保裁剪和调整图像大小与输入图像(删除背景)具有相同的质量?
问题是原始 PNG 具有嵌入的颜色配置文件,并且在保存新图像时该配置文件没有被传输。
下面的代码解决了这个问题:
profile = resized_image.info.get("icc_profile", "")
final_image.save(final_img_path, format="PNG", icc_profile=profile)