python自适应调整色彩饱和度
时间: 2023-06-29 09:06:02 浏览: 105
要自适应调整图片的色彩饱和度,可以使用Python的Pillow库。以下是一个示例代码:
```python
from PIL import Image, ImageEnhance
def auto_adjust_saturation(image_path):
# 打开图片
image = Image.open(image_path)
# 计算平均亮度
pixels = image.load()
width, height = image.size
total_brightness = 0
for y in range(height):
for x in range(width):
r, g, b = pixels[x, y]
total_brightness += 0.299 * r + 0.587 * g + 0.114 * b
average_brightness = total_brightness / (width * height)
# 计算平均色彩饱和度
total_saturation = 0
for y in range(height):
for x in range(width):
r, g, b = pixels[x, y]
gray = 0.299 * r + 0.587 * g + 0.114 * b
saturation = 0 if gray == 0 else (max(r, g, b) - min(r, g, b)) / gray
total_saturation += saturation
average_saturation = total_saturation / (width * height)
# 调整饱和度
saturation_factor = average_saturation / 0.5
saturation_factor = max(0, min(saturation_factor, 2))
enhancer = ImageEnhance.Color(image)
image = enhancer.enhance(saturation_factor)
# 保存图片
image.save('output.jpg')
# 示例用法
auto_adjust_saturation('input.jpg')
```
该代码会自适应计算输入图片的平均亮度和平均色彩饱和度,然后根据平均色彩饱和度调整饱和度,最终输出调整后的图片。你可以根据需要修改代码中的参数来调整饱和度调整的效果。
阅读全文