双线性缩放实战:输入输出都从零编号,为什么采样位置仍可能是负四分之一
同样叫双线性缩放,两份程序也可能输出不同像素,因为它们先把目标像素映射到源图的位置就不相同。半像素约定对齐的是像素格子的整体范围,align-corners对齐的是两端像素中心;四点加权只是后半步。

下标零不等于图像左边界
把像素中心编号为零、一、二,像素格子的外侧边界自然位于负二分之一和最后中心再加二分之一。半像素映射把目标中心j换成源坐标(j+1/2)×输入长度/输出长度−1/2。
长度二放大到四时,源坐标依次为−1/4、1/4、3/4、5/4。第一个位置虽然为负,却不是数组越界访问指令;它表示采样中心落在原图首个中心左侧,需要交给边界延拓规则处理。
对齐两端中心会得到另一组坐标
align-corners在输出长度大于一时使用j×(输入长度−1)/(输出长度−1)。长度二变四,位置为零、三分之一、三分之二、一,端点中心恰好重合。
两种映射各有清楚含义,不能把其中一种描述成所有场景唯一正确。ONNX Resize规范分别列出这些坐标模式,也单独列出pytorch-half-pixel等变体。本文只实现明确写出的两种,不宣称覆盖规范的全部模式和参数。
本文使用边缘值延拓
算出源坐标后,先夹到零至输入长度减一之间,再找相邻中心和插值权重。越过左端继续使用首像素,越过右端继续使用末像素,等价于边缘值向外保持常数。
这不是零填充,也不是把越界坐标直接作为Python负下标。不同边界策略会影响最外侧像素,即使两份程序使用相同坐标公式也可能不同。本文的夹边规则是自己的完整接口合同,引用ONNX主要用于核对坐标定义。
两个像素足以看到结果差异
源行[0,12]放大到四格,半像素加边缘延拓得到[0,3,9,12];对齐两端中心则得到[0,4,8,12]。两端相同,中间不同,差别发生在采样位置,而不是四则运算误差。
输出长度只有一时,普通half-pixel会采源图中心,因此本例得到六。align-corners的分母此时为零,本文明确规定该退化轴采源坐标零,得到零。不能让除零异常或某个未说明的库默认值替代合同。
二维计算是两方向线性权重的乘积
源坐标(sx,sy)落在相邻四个像素中心之间。横向小数部分wx、纵向小数部分wy给出四个权重:(1−wx)(1−wy)、wx(1−wy)、(1−wx)wy、wxwy。
四权重非负且和为一,因此输出处于四个参与值的最小最大之间。源码先在上下两行各插值,再按纵向权重混合;这与四项直接相加等价,不需要对二维图像建立一个全局多项式。
精确线性斜坡是有力的裁判
若源图值为7+3x−2y,双线性插值在夹边后的源坐标上应精确等于同一个表达式。测试直接把映射位置代入平面公式,不复用四个像素权重计算,可以检查横纵坐标、尺寸比例和边界处理。
输入高宽与输出高宽分别遍历一至五,再配两种坐标模式,共1250份形状模式组合,全部用Fraction比较。另有任意小图同尺寸恒等、单像素扩展和输出零尺寸拒绝检查。
缩小不是自动抗混叠
双线性插值能定义每个采样值,却不等于针对任意缩小比例做了充分低通滤波。高频棋盘在下采样时仍可能产生混叠。要比较抗混叠效果,必须另行约定滤波核、支持范围和边界模式。
本文也没有做RGB伽马校正;直接对编码颜色数值插值与在线性光空间插值并不相同。所有样本都是精确标量数组,适合检查坐标合同,不代表对真实照片或模型输入质量做过实验。
完整程序与本次实测输出
保存为demo.py,执行python3 demo.py。本次使用Linux、CPython 3.12.14与标准库,退出码为0,标准错误为空。程序仅使用内存教学样本,不访问网络或业务文件。
from fractions import Fraction as F
from itertools import product
def coordinate(j, source, target, align):
if align:
return F(j*(source-1), target-1) if target > 1 else F(0)
return F((2*j+1)*source, 2*target)-F(1, 2)
def resize(image, height, width, align=False):
if (type(image) is not list or not image or any(type(r) is not list for r in image)
or not image[0] or any(len(r) != len(image[0]) for r in image)
or any(type(v) not in (int, F) for r in image for v in r)
or any(type(v) is not int or not 1 <= v <= 32 for v in (height, width))
or len(image) > 32 or len(image[0]) > 32 or type(align) is not bool):
raise ValueError('exact nonempty image and output sizes1..32 required')
h, w = len(image), len(image[0])
result = []
for y in range(height):
sy = min(F(h-1), max(F(0), coordinate(y, h, height, align)))
y0 = sy.numerator//sy.denominator
y1, wy = min(y0+1, h-1), sy-y0
row = []
for x in range(width):
sx = min(F(w-1), max(F(0), coordinate(x, w, width, align)))
x0 = sx.numerator//sx.denominator
x1, wx = min(x0+1, w-1), sx-x0
row.append((1-wy)*((1-wx)*image[y0][x0]+wx*image[y0][x1])
+ wy*((1-wx)*image[y1][x0]+wx*image[y1][x1]))
result.append(row)
return result
def main():
print('2-to4 half-pixel coordinates:', [str(coordinate(j, 2, 4, False)) for j in range(4)])
print('half-pixel row:', list(map(str, resize([[0, 12]], 1, 4)[0])))
print('align-corners row:', list(map(str, resize([[0, 12]], 1, 4, True)[0])))
assert resize([[0, 12]], 1, 4)[0] == [0, 3, 9, 12]
assert resize([[0, 12]], 1, 4, True)[0] == [0, 4, 8, 12]
print('2-to1 half/align:', resize([[0, 12]], 1, 1)[0][0], resize([[0, 12]], 1, 1, True)[0][0])
checks = 0
for h, w, oh, ow, align in product(range(1, 6), range(1, 6), range(1, 6), range(1, 6), (False, True)):
# Bilinear interpolation reproduces an affine plane at clamped coordinates.
image = [[7+3*x-2*y for x in range(w)] for y in range(h)]
out = resize(image, oh, ow, align)
for y in range(oh):
for x in range(ow):
if align:
sy = F(y*(h-1), oh-1) if oh > 1 else F(0)
sx = F(x*(w-1), ow-1) if ow > 1 else F(0)
else:
sy = F((2*y+1)*h-oh, 2*oh)
sx = F((2*x+1)*w-ow, 2*ow)
sy, sx = min(h-1, max(0, sy)), min(w-1, max(0, sx))
assert out[y][x] == 7+3*sx-2*sy
checks += 1
a = [[1, 3, 9], [4, -2, 5]]
assert resize(a, 2, 3) == a
assert resize([[8]], 3, 4) == [[8]*4 for _ in range(3)]
print('affine-plane shape/mode comparisons:', checks)
try:
resize(a, 0, 4)
except ValueError:
print('identity, single input pixel and invalid size: PASS')
else:
raise AssertionError('zero size accepted')
if __name__ == '__main__':
main()2-to4 half-pixel coordinates: ['-1/4', '1/4', '3/4', '5/4'] half-pixel row: ['0', '3', '9', '12'] align-corners row: ['0', '4', '8', '12'] 2-to1 half/align: 6 0 affine-plane shape/mode comparisons: 1250 identity, single input pixel and invalid size: PASS
来源与复现范围
资料核对与本地运行日期为2026年10月8日。本文解释、程序与测试数据独立编写,引用资料用于确认算法定义及适用前提;有限测试不等于生产系统性能或全部输入保证。

