You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python通过图像自身反射填充背景生成正方形TIF图像?

使用PIL实现TIF图像对称反射填充生成正方形

核心方案

利用PIL内置的图像翻转工具,结合画布粘贴操作,高效实现对称反射填充,替代手动逐行复制数组的低效方式,精准达成对称效果。

步骤与代码实现

  1. 确定目标尺寸:以图像宽高的最大值作为正方形边长,计算左右、上下的对称填充量。
  2. 反射填充操作:通过ImageOps.mirror(水平翻转)和ImageOps.flip(垂直翻转)生成反射区域,粘贴到空白画布的对应位置。

直接运行的代码示例:

from PIL import Image, ImageOps

def reflect_to_square(img):
    w, h = img.size
    target_size = max(w, h)
    
    # 计算对称填充量
    pad_l = (target_size - w) // 2
    pad_r = target_size - w - pad_l
    pad_t = (target_size - h) // 2
    pad_b = target_size - h - pad_t
    
    # 创建空白正方形画布
    square_canvas = Image.new(img.mode, (target_size, target_size), 0)
    # 粘贴原图到中心
    square_canvas.paste(img, (pad_l, pad_t))
    
    # 填充左右反射区域
    if pad_l > 0:
        left_reflect = ImageOps.mirror(img.crop((0, 0, pad_l, h)))
        square_canvas.paste(left_reflect, (0, pad_t))
    if pad_r > 0:
        right_reflect = ImageOps.mirror(img.crop((w - pad_r, 0, w, h)))
        square_canvas.paste(right_reflect, (w + pad_l, pad_t))
    
    # 填充上下反射区域(含已填充左右的中间区域)
    if pad_t > 0:
        top_region = square_canvas.crop((0, pad_t, target_size, pad_t + pad_t))
        top_reflect = ImageOps.flip(top_region)
        square_canvas.paste(top_reflect, (0, 0))
    if pad_b > 0:
        bottom_region = square_canvas.crop((0, h + pad_t - pad_b, target_size, h + pad_t))
        bottom_reflect = ImageOps.flip(bottom_region)
        square_canvas.paste(bottom_reflect, (0, h + pad_t))
    
    return square_canvas

# 示例调用
if __name__ == "__main__":
    input_img = Image.open("input_image.tif")
    result_img = reflect_to_square(input_img)
    result_img.save("output_square.tif")

关键说明

  • 全程使用PIL原生工具,避免NumPy数组的繁琐操作,效率更高。
  • 先填充左右再处理上下,确保四个角落的反射区域也能完美对称。
  • 兼容单通道/多通道TIF图像,保持原图像色彩模式与细节不变。

内容的提问来源于stack exchange,提问作者gram_schmidt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 00:10:36