How do you letterbox a wide image to a fixed square?
pad preserves content proportions and fills the unused area with a chosen color to produce the exact target size.
Pixel experiment and interpretation
Put a gray banner on a black square and compare its corner and center. Record the offset to map detections back to the source.
from PIL import Image, ImageOps
im=ImageOps.pad(Image.new('L',(4,2),99),(4,4),color=0)
(im.getpixel((0,0)),im.getpixel((2,2)))Result (0, 99)
中文
如何把宽幅图片装入固定方框并保留上下留白?
pad 保持内容比例并用指定颜色填满多余区域,输出恰好是目标尺寸。
像素实验与适用边界
把灰色横幅放进黑底方框,观察角点与中心像素。训练时记录留白偏移,才能把检测框映射回原图。
from PIL import Image, ImageOps
im=ImageOps.pad(Image.new('L',(4,2),99),(4,4),color=0)
(im.getpixel((0,0)),im.getpixel((2,2)))结果 (0, 99)