批量处理图片对比度python
时间: 2024-12-06 17:04:59 浏览: 40
批量处理图片对比度在Python中通常通过图像处理库如PIL (Pillow) 或者更强大的OpenCV来实现。以下是一个简单的步骤概述:
1. 导入必要的库:
```python
from PIL import Image
import os
```
2. 定义一个函数来调整图片对比度:
```python
def adjust_contrast(image_path, contrast_factor):
with Image.open(image_path) as img:
# 使用ImageEnhance模块调整对比度
enhancer = ImageEnhance.Contrast(img)
new_img = enhancer.enhance(contrast_factor)
return new_img
```
3. 循环遍历目录中的所有图片,并应用对比度调整:
```python
base_dir = "your_image_directory"
output_dir = "output_directory"
for filename in os.listdir(base_dir):
if filename.endswith(".jpg") or filename.endswith(".png"): # 可视化只处理特定类型的文件
input_path = os.path.join(base_dir, filename)
output_path = os.path.join(output_dir, filename)
adjusted_img = adjust_contrast(input_path, contrast_factor=1.5) # 调整对比度值
adjusted_img.save(output_path)
```
4. **相关问题**:
- 图片对比度调整的具体算法是什么?
- 如何保存调整后的图片保持原始尺寸不变?
- 如果需要同时改变亮度和饱和度怎么办?
记得替换`base_dir`和`output_dir`为你实际的图片源目录和目标输出目录。
阅读全文
相关推荐


















