修改图像对比度 原理详解

代码调用:

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

相关推荐
serve the people2 小时前
机器学习(ML)和人工智能(AI)技术在WAF安防中的应用
人工智能·机器学习
0***K8922 小时前
前端机器学习
人工智能·机器学习
陈天伟教授2 小时前
基于学习的人工智能(5)机器学习基本框架
人工智能·学习·机器学习
m0_650108242 小时前
PaLM-E:具身智能的多模态语言模型新范式
论文阅读·人工智能·机器人·具身智能·多模态大语言模型·palm-e·大模型驱动
zandy10112 小时前
2025年11月AI IDE权深度测榜:深度分析不同场景的落地选型攻略
ide·人工智能·ai编程·ai代码·腾讯云ai代码助手
欢喜躲在眉梢里2 小时前
CANN 异构计算架构实操指南:从环境部署到 AI 任务加速全流程
运维·服务器·人工智能·ai·架构·计算
0***R5152 小时前
人工智能在金融风控中的应用
人工智能
2501_941403762 小时前
人工智能赋能智慧金融互联网应用:智能风控、个性化理财与金融服务优化实践探索》
人工智能
youngerwang3 小时前
【字节跳动 AI 原生 IDE TRAE 】
ide·人工智能·trae
youngerwang3 小时前
AI 编程环境与主流 AI IDE 对比分析报告
ide·人工智能