gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
帮我写一个用bicubic下采样图像的python代码
- User
帮我写一个用bicubic下采样图像的python代码
- Assistant
当然可以!下面是一个使用Python实现bicubic下采样(图像缩小)的示例代码。这里我们用到的是Pillow库,它内置了bicubic插值方法。
from PIL import Image def bicubic_downsample(input_path, output_path, scale_factor): """ 用bicubic插值对图像进行下采样。 参数: - input_path: 输入图像路径 - output_path: 输出图像路径 - scale_factor: 缩放因子,例如2表示宽和高均缩小至原来的一半 """ # 打开图像 img = Image.open(input_path) # 计算新尺寸 new_width = int(img.width / scale_factor) new_height = int(img.height / scale_factor) # 进行下采样,使用BICUBIC插值 img_downsampled = img.resize((new_width, new_height), Image.BICUBIC) # 保存结果 img_downsampled.save(output_path) print(f"图像已下采样并保存至 {output_path}") # 示例使用 if __name__ == "__main__": bicubic_downsample("input.jpg", "output_downsampled.jpg", scale_factor=2)说明:
- 需要先安装Pillow库:
pip install Pillow scale_factor表示缩放的倍数,2就是把图像尺寸缩到一半(宽和高都是1/2)
如果你有更复杂的需求,比如读取numpy数组进行下采样,也可以告诉我,我可以帮你写基于OpenCV或scipy的版本。
- 需要先安装Pillow库: