用python写一个批量下采样文件夹下所有图片的程序
时间: 2023-05-17 18:04:38 浏览: 118
可以使用Pillow库来实现这个功能,以下是示例代码:
```python
from PIL import Image
import os
def downsample_images(folder_path, output_folder, factor):
for filename in os.listdir(folder_path):
if filename.endswith('.jpg') or filename.endswith('.png'):
image_path = os.path.join(folder_path, filename)
with Image.open(image_path) as img:
width, height = img.size
new_size = (int(width/factor), int(height/factor))
img = img.resize(new_size, resample=Image.BICUBIC)
output_path = os.path.join(output_folder, filename)
img.save(output_path)
# 示例用法
downsample_images('input_folder', 'output_folder', 2)
```
这个程序会将输入文件夹中所有的jpg和png图片下采样到原来的1/2大小,并保存到输出文件夹中。你可以修改factor参数来控制下采样的程度。
阅读全文