基于Python和OpenCV:保持宽高比将图像调整为正方形
Python + OpenCV:将图像转为带白色背景的正方形(保持宽高比)
嗨,这个需求很常见,我来给你一套简洁的实现方案!核心逻辑是先以原图的最长边为边长创建白色正方形背景,再把原图按原比例居中放置到背景上,完美匹配你想要的效果。
完整代码实现
import cv2 import numpy as np def convert_to_square_with_white_bg(input_path, output_path): # 读取输入图像 img = cv2.imread(input_path) if img is None: raise ValueError("无法读取图像,请检查路径是否正确") # 获取原图的宽高 h, w = img.shape[:2] # 确定正方形的边长(取宽高中的最大值) square_size = max(w, h) # 创建白色背景的正方形图像(3通道,uint8类型) white_bg = np.ones((square_size, square_size, 3), dtype=np.uint8) * 255 # 计算原图在背景中的偏移量,实现居中放置 x_offset = (square_size - w) // 2 y_offset = (square_size - h) // 2 # 将原图粘贴到白色背景的对应位置 white_bg[y_offset:y_offset+h, x_offset:x_offset+w] = img # 保存处理后的图像 cv2.imwrite(output_path, white_bg) print(f"处理完成,已保存至 {output_path}") # 调用示例 convert_to_square_with_white_bg("input.png", "output.jpg")
代码细节解释
- 图像读取校验:增加了空值判断,避免因路径错误或文件损坏导致的程序崩溃。
- 正方形尺寸确定:取原图宽、高的最大值作为边长,确保原图能完整放入背景,同时最小化空白区域。
- 白色背景生成:用
np.ones创建全1数组,乘以255得到标准的纯白色3通道图像,和原图色彩通道一致。 - 居中逻辑:通过计算水平和垂直方向的偏移量,让原图在正方形背景中完美居中,视觉上更协调。
- 格式兼容:支持PNG、JPG等常见图像格式的输入输出,无需额外转换。
补充:处理透明背景的RGBA图像
如果你的输入图像是带透明通道的PNG,可以先把透明区域转为白色背景,再执行上述逻辑:
def convert_rgba_to_square_with_white_bg(input_path, output_path): img = cv2.imread(input_path, cv2.IMREAD_UNCHANGED) if img is None: raise ValueError("无法读取图像,请检查路径是否正确") # 如果是RGBA图像,将透明通道转为白色背景 if img.shape[2] == 4: alpha_channel = img[:, :, 3] rgb_channels = img[:, :, :3] white_bg = np.ones_like(rgb_channels) * 255 # 根据透明通道混合背景与原图 img = np.where(alpha_channel[:, :, np.newaxis] == 0, white_bg, rgb_channels) # 后续步骤和基础版本一致 h, w = img.shape[:2] square_size = max(w, h) white_bg = np.ones((square_size, square_size, 3), dtype=np.uint8) * 255 x_offset = (square_size - w) // 2 y_offset = (square_size - h) // 2 white_bg[y_offset:y_offset+h, x_offset:x_offset+w] = img cv2.imwrite(output_path, white_bg) print(f"处理完成,已保存至 {output_path}")
内容的提问来源于stack exchange,提问作者Nguyễn Trọng Hiển
相关产品推荐
相关产品推荐

