修改图像对比度 原理详解

代码调用:

python 复制代码
image = Image.open(os.path.join(filepath,filename))
enhancer = ImageEnhance.Contrast(image)
enhanced_image = enhancer.enhance(2.0)
enhanced_image.save(os.path.join(dest_address, filename))
python 复制代码
class Contrast(_Enhance):
    """Adjust image contrast.

    This class can be used to control the contrast of an image, similar
    to the contrast control on a TV set. An enhancement factor of 0.0
    gives a solid grey image. A factor of 1.0 gives the original image.
    """

    def __init__(self, image):
        self.image = image
        mean = int(ImageStat.Stat(image.convert("L")).mean[0] + 0.5)
        # ImageStat.Stat 函数计算图像的均值,这里是将图像转换为灰度模式("L",即 luminance)后计算的均值。
        # 然后,将计算得到的均值四舍五入取整,存储在变量 mean 中。
        self.degenerate = Image.new("L", image.size, mean).convert(image.mode)
		# 创建一个与传入的图像尺寸相同的新图像,使用先前计算得到的均值填充所有像素,称为 "degenerate" 图像,意思是它是一个像素均值相同的图像。
		# 然后,通过 .convert(image.mode) 将其转换为与原始图像相同的颜色模式,以确保图像通道匹配。
        if "A" in image.getbands():
        # 检查原始图像是否包含透明度通道(Alpha 通道)。透明度通道在图像中通常用于控制像素的透明度级别。
            self.degenerate.putalpha(image.getchannel("A"))
            # 如果图像包含透明度通道,这一行代码将使用 image.getchannel("A") 获取原始图像的 Alpha 通道,并将它应用于 self.degenerate 图像,以使新图像也具有相同的透明度通道。
            # 这样做是为了确保在使用透明度信息的时候,新的 "degenerate" 图像与原始图像一致。

实际是将所有像素均值新单色图片和原图片按blend第三个参数的比例混合。

blend_img = Image.blend(img1, img2, alpha)

blend_img = img1 * (1 -- alpha) + img2* alpha

相关推荐
`流年づ6 小时前
人工智能学习笔记-Transformer
人工智能·深度学习·transformer
Wanderer X6 小时前
【ML】rope
人工智能
nVisual6 小时前
nVisual:AI驱动的智能排障,平均响应时间缩短40%
android·人工智能·缓存
白日做梦Q7 小时前
PyTorch从零手写CNN实现NEU钢材表面缺陷检测(完整实战·单篇完结)
人工智能·pytorch·cnn
星马梦缘7 小时前
机器学习与模式识别 第十一章 优化于梯度下降 考点压缩
人工智能·机器学习·梯度下降·hessian·条件数
想会飞的蒲公英7 小时前
TF-IDF + 随机森林中文文本分类全链路实战:从训练脚本到 Flask API + Streamlit 前端
人工智能·pytorch·python·随机森林·分类·flask·tf-idf
AI服务老曹7 小时前
摄像机安装AI视频分析参数配置说明:POC现场交付全流程指南
人工智能·音视频
FriendshipT7 小时前
Ultralytics:解读C3模块
人工智能·pytorch·python·深度学习·目标检测
极光代码工作室7 小时前
基于深度学习的异常行为检测系统
人工智能·python·深度学习·神经网络·机器学习
阿拉斯攀登7 小时前
RAG 性能优化:缓存、批量与并发
人工智能·缓存·性能优化·embedding·agent·loop·rag