修改图像对比度 原理详解

代码调用:

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

相关推荐
人工智能AI技术5 分钟前
Gemma 4 C# 部署教程:手机/边缘设备离线运行
人工智能
JHC0000007 小时前
基于Ollama,Milvus构建的建议知识检索系统
人工智能·python·milvus
ZPC82107 小时前
如何创建一个单例类 (Singleton)
开发语言·前端·人工智能
AppOS7 小时前
手把手教你 Openclaw 在 Mac 上本地化部署,保姆级教程!接入飞书打造私人 AI 助手
人工智能·macos·飞书
workflower8 小时前
AI制造-推荐初始步骤
java·开发语言·人工智能·软件工程·制造·需求分析·软件需求
wukangjupingbb8 小时前
解析Computational driven drug discovery: from structure to clinic
人工智能·机器学习
tctasia8 小时前
TCT Asia 2026现场观察:中国增材制造,已经进入“规模化时刻”(上)
大数据·人工智能·制造
AI周红伟8 小时前
AI自动盯盘与定时行情分析:OpenClaw股票辅助Agent集成完整使用指南-周红伟
运维·服务器·人工智能·音视频·火山引擎
Legend NO248 小时前
大模型与知识图谱的协同技术体系
人工智能·自然语言处理·知识图谱