实现图像的灰度变换,包括图像变暗、图像变亮、降低对比度和直方图均衡化处理python
时间: 2024-10-19 14:05:06 浏览: 173
在Python中,我们可以使用PIL(Python Imaging Library)或其更现代的替代品Pillow库来进行图像的灰度变换。以下是一些基本操作的示例:
1. 图像变暗 (Brightness Decrease):
```python
from PIL import Image, ImageEnhance
def darken_image(img_path, factor=0.5):
img = Image.open(img_path)
enhancer = ImageEnhance.Brightness(img)
dark_img = enhancer.enhance(factor)
return dark_img.save('dark_' + img_path)
# 使用方法
darken_image('original.jpg')
```
2. 图像变亮 (Brightness Increase):
```python
def lighten_image(img_path, factor=1.5):
# 类似于上述代码,只是将factor设为大于1的值
return darken_image(img_path, factor)
```
3. 降低对比度 (Decrease Contrast):
```python
def decrease_contrast(img_path, factor=0.5):
img = Image.open(img_path)
enhancer = ImageEnhance.Contrast(img)
low_contrast_img = enhancer.enhance(factor)
return low_contrast_img.save('low_contrast_' + img_path)
```
4. 直方图均衡化 (Histogram Equalization):
```python
from PIL import ImageOps
def histogram_equalization(img_path):
img = Image.open(img_path).convert('L') # 转换为灰度
eq_img = ImageOps.equalize(img)
return eq_img.save('eq_' + img_path)
```
每个函数都接受一个输入图片路径,并对图片进行相应的灰度变换处理。注意,`factor`是一个调整比例的参数,通常取值范围在0到2之间。
阅读全文
相关推荐


















