修改图像对比度 原理详解

代码调用:

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

相关推荐
Zy宇19 分钟前
从养 OpenClaw 到养社区 AI:一套 Multi-Agent 社区的设计思路
人工智能·ai
雪隐1 小时前
个人电脑玩AI-06让5060 Ti给你打工——Qwen3.6-35B-A3B + LM Studio + openWebUI
人工智能·后端
得物技术1 小时前
从表单到 Agent:得物社区活动搭建的 AI 实践之路
人工智能·架构·agent
Weigang1 小时前
给 Agent 接入 Qdrant 前,先写清楚检索合同
人工智能
字节跳动数据库1 小时前
文章分享——庖丁解牛-图解查询分析和调优利器Optimizer Trace
人工智能·程序员
以和为贵2 小时前
前端手写 RAG 踩坑实录:四个让检索"翻车"的坑
前端·人工智能·面试
何时梦醒2 小时前
深入理解 LLM Tokenization:从文本分词到语义向量化的完整旅程
人工智能
冬哥聊AI2 小时前
阿里二面:8K Token 撑住 100 轮对话,你的分层记忆架构怎么设计?
人工智能
拾年2752 小时前
我用 30 行代码,搞懂了大模型是怎么"读"中文的
javascript·人工智能·llm
Tigger2 小时前
受不了 ¥98/年的订阅,我用 Vibe Coding 自己写了个剪贴板工具
人工智能·开源·mac