python如何批量处理图像尺寸
时间: 2024-10-15 21:01:30 浏览: 37
在Python中,批量处理图像尺寸通常可以使用PIL(Pillow库)或者OpenCV等图像处理库来完成。这里是一个基本的例子,假设你想将一组图片文件统一调整到特定的宽度和高度:
```python
from PIL import Image
# 定义目标尺寸
target_width = 800
target_height = 600
# 指定图片保存的路径
image_dir = 'path/to/your/images'
for filename in os.listdir(image_dir):
if filename.endswith(".jpg") or filename.endswith(".png"): # 只处理.jpg和.png格式的图片
img_path = os.path.join(image_dir, filename)
with Image.open(img_path) as im:
# 调整图片大小并保持宽高比
resized_img = im.resize((target_width, target_height), Image.ANTIALIAS)
# 保存处理后的图片
new_img_path = os.path.join(image_dir, "resized_" + filename)
resized_img.save(new_img_path)
```
在这个例子中,我们首先打开每个图片,然后使用`resize()`函数调整尺寸,同时`Image.ANTIALIAS`用于提供抗锯齿效果。最后,我们将处理后的图片保存到原目录下的一个新的文件。
阅读全文
相关推荐
















