如何调整图片底部宽度并保留顶部宽度?Python实现方案咨询
实现底部加宽的地毯图片变形脚本
原代码的问题在于仅做了缩放后裁剪,并未实现「顶部宽度不变、底部宽度增大」的梯形变形效果。要达成需求,我们可以用PIL的透视变换来实现,同时支持命令行传参调用。
步骤说明
- 读取输入图片,获取原始宽高
- 保持顶部宽度与原图一致,将底部宽度设为传入的目标值
- 计算透视变换的顶点坐标:顶部左右顶点保留原位置,底部左右顶点向外扩展至目标宽度
- 执行透视变换生成变形后的图片
- 保存结果文件
完整代码
from PIL import Image import sys def widen_rug_bottom(input_path, new_bottom_width): # 打开目标图片 img = Image.open(input_path) orig_width, orig_height = img.size # 顶部宽度沿用原图宽度,底部宽度取传入的参数值 top_width = orig_width bottom_width = int(new_bottom_width) # 定义原始图片与变形后图片的顶点映射关系 src_points = [ (0, 0), (orig_width, 0), (0, orig_height), (orig_width, orig_height) ] dest_points = [ (0, 0), (top_width, 0), ((bottom_width - top_width) // 2, orig_height), (top_width + (bottom_width - top_width) // 2, orig_height) ] # 应用透视变换,使用BICUBIC插值保证画质 transformed_img = img.transform( (bottom_width, orig_height), Image.PERSPECTIVE, Image.quad_to_quad(src_points, dest_points), Image.BICUBIC ) # 生成输出文件名并保存 output_path = f"widened_{input_path}" transformed_img.save(output_path) print(f"变形后的图片已保存至: {output_path}") if __name__ == "__main__": # 校验命令行参数格式 if len(sys.argv) != 3: print("用法: python rug.py \"input_img.jpg\" \"new_bottom_width\"") sys.exit(1) input_img = sys.argv[1] new_bottom_w = sys.argv[2] try: widen_rug_bottom(input_img, new_bottom_w) except Exception as e: print(f"处理出错: {str(e)}")
使用说明
- 先安装依赖库:
pip install pillow - 执行命令示例:
python rug.py "input_img.jpg" "800"(其中800是你需要的底部宽度) - 脚本会自动生成名为
widened_input_img.jpg的变形后图片
代码解释
- 透视变换:通过
Image.transform的PERSPECTIVE模式,将原图的矩形顶点映射为目标梯形顶点,实现上窄下宽的自然变形 - 命令行适配:用
sys.argv读取外部参数,让脚本可以灵活处理不同图片和宽度需求 - 居中变形:底部左右顶点对称扩展,保证地毯图案在变形后保持居中,避免偏移
内容的提问来源于stack exchange,提问作者memes garage
相关产品推荐
相关产品推荐

