修改图像对比度 原理详解

代码调用:

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

相关推荐
飞哥数智坊9 小时前
GPT-5-Codex 发布,Codex 正在取代 Claude
人工智能·ai编程
倔强青铜三9 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
虫无涯10 小时前
Dify Agent + AntV 实战:从 0 到 1 打造数据可视化解决方案
人工智能
Dm_dotnet12 小时前
公益站Agent Router注册送200刀额度竟然是真的
人工智能
算家计算13 小时前
7B参数拿下30个世界第一!Hunyuan-MT-7B本地部署教程:腾讯混元开源业界首个翻译集成模型
人工智能·开源
机器之心13 小时前
LLM开源2.0大洗牌:60个出局,39个上桌,AI Coding疯魔,TensorFlow已死
人工智能·openai
Juchecar14 小时前
交叉熵:深度学习中最常用的损失函数
人工智能
林木森ai14 小时前
爆款AI动物运动会视频,用Coze(扣子)一键搞定全流程(附保姆级拆解)
人工智能·aigc
聚客AI15 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
BeerBear16 小时前
【保姆级教程-从0开始开发MCP服务器】一、MCP学习压根没有你想象得那么难!.md
人工智能·mcp