Loading... 将长方形的图片归一化成,以短的边去限制长的边,下面是效果图  # 代码 ```python image_path = "path_to_your_image.png" from PIL import Image import numpy as np import matplotlib.pyplot as plt def normalize_to_square(image_path): # 打开图片 img = Image.open(image_path) print("原始尺寸 (宽, 高):", img.size) # 打印原始尺寸 # 如果是RGBA模式,转换为RGB if img.mode == 'RGBA': img = img.convert('RGB') # 获取原始宽高 width, height = img.size min_dim = min(width, height) # 以最短边作为正方形边长 # 创建黑色背景的正方形 square_img = Image.new('RGB', (min_dim, min_dim), (0, 0, 0)) # 如果宽>高,缩放宽度到min_dim;如果高>宽,缩放高度到min_dim if width > height: resized_img = img.resize((min_dim, height), Image.Resampling.LANCZOS) square_img.paste(resized_img, (0, 0)) else: resized_img = img.resize((width, min_dim), Image.Resampling.LANCZOS) square_img.paste(resized_img, (0, 0)) # 转换为数组 img_array = np.array(square_img, dtype=float) # 像素值归一化到0-1 normalized_img = img_array / 255.0 # 保存结果为PNG normalized_img_pil = Image.fromarray((normalized_img * 255).astype(np.uint8)) normalized_img_pil.save("out_put.png", "PNG") # 打印最终尺寸 final_width, final_height = square_img.size print("处理后尺寸 (宽, 高):", (final_width, final_height)) return img_array, normalized_img # 显示图片 def show_images(original, normalized): plt.figure(figsize=(12, 6)) plt.subplot(1, 2, 1) plt.title("Original Square Image") plt.imshow(original.astype(np.uint8)) plt.axis('off') plt.subplot(1, 2, 2) plt.title("Normalized Square Image") plt.imshow(normalized) plt.axis('off') plt.show() # 示例用法 original_img, normalized_result = normalize_to_square(image_path) # 显示图片 show_images(original_img, normalized_result) ``` 最后修改:2025 年 02 月 27 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏