Python基于bilinear interpolation实现图像缩放仅角落值正确求助
双线性插值图像缩放问题修复
问题根因
你的代码存在两处核心错误:
- 坐标映射逻辑错误:原图像像素的索引范围是
0 ~ 原始宽度-1、0 ~ 原始高度-1,你在做新坐标到原坐标的映射时,直接乘以了原始长宽的数值,而不是最大索引值,导致中间坐标的映射位置偏移。 - 插值权重计算错误:双线性插值的权重应该使用当前采样点相对于左上角相邻像素的相对偏移量,而不是采样点在原图的全局坐标,当全局坐标大于1时,权重会出现负数/超出[0,1]范围的问题,计算结果完全错误。
修复后代码
import math def bilinear_interpolation(image, y, x): height = len(image) width = len(image[0]) x1 = min(math.floor(x), width - 1) y1 = min(math.floor(y), height - 1) x2 = min(math.ceil(x), width - 1) y2 = min(math.ceil(y), height - 1) # 计算相对偏移量 dx = x - x1 dy = y - y1 a = image[y1][x1] b = image[y2][x1] c = image[y1][x2] d = image[y2][x2] # 用相对偏移量计算权重 new_pixel = a * (1 - dx) * (1 - dy) new_pixel += b * dy * (1 - dx) new_pixel += c * dx * (1 - dy) new_pixel += d * dx * dy return round(new_pixel) def resize(image, new_height, new_width): old_height = len(image) old_width = len(image[0]) new_image = [[0 for _ in range(new_width)] for _ in range(new_height)] for y in range(new_height): for x in range(new_width): # 映射到原图像的最大索引范围 x_ = (x / (new_width - 1)) * (old_width - 1) y_ = (y / (new_height - 1)) * (old_height - 1) new_image[y][x] = bilinear_interpolation(image, y_, x_) return new_image
结果验证
用你提供的4×4测试矩阵缩放至3行2列:
测试输入:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
运行修复后代码输出为:
[[1, 4], [7, 10], [13, 16]]
和预期结果完全一致。
内容的提问来源于stack exchange,提问作者Daniel E
相关产品推荐
相关产品推荐

