图像处理——对比度调整算法(python语言)

  • Post author:
  • Post category:python



对比度调整算法说明(完整python代码在文末)





本算法主要是对RGB空间进行调整。设定合适的RGB阈值,并在此阈值基础上计算出合适的调整系数进行对比度调整。阈值作为对比度调整依据,当对比度调整为-1时,图像RGB各分量都等于阀值,图像呈全灰色,灰度图上只有一种颜色,即阀值灰度。其算法实现如下:



1)


比较当前像素点三维颜色值与阈值的大小,并获取其差值。



2)


当增大对比度时,利用调整系数来指数的放大差值;当减小对比度时,利用调整系数来线性的减小差值;当对比度增量为-1时,差值即减小为0。



例如:当前像素点为(50,200,250),阈值为200;对比度增大后可能为(10,200,255),对比度减小后可能为(150,200,210)。



(不明白可以的,可以参考CSDN博客:

https://blog.csdn.net/maozefa/article/details/7069001


完整python代码如下:

运行方式:打开终端界面,在该py文件目录下,运行:

python  该文件.py  图片路径  对比度等级(-1~1)  阈值(默认0.5,可忽略)

例如:python  Contrast.py  C:\Users\PDD\Desktop\pdd.jpg  0.8 (0.5)

import cv2
import sys
import numpy as np
import matplotlib.pyplot as plt

"""
  对比度调整算法:
  主要是对RGB空间进行调整。设定合适的RGB阈值,并在此阈值基础上计算出合适的调整系数进行对比度调整。
  参考CSDN博客:https://blog.csdn.net/maozefa/article/details/7069001
"""
def ContrastAlgorithm(rgb_img, contrast=0.5, threshold=0.5):
    img = rgb_img * 1.0
    img_out = img
    
    # 增量等于1,按灰度阈值最多调整成八种颜色:
    # 黑、红、绿、蓝、黄(255,255,0)、品红(255,0,255)、青(0,255,255)、白
    if contrast == 1:
        # newRGB = RGB >= Threshold? 255 : 0
        mask_1 = img >= threshold*255.0
        rgb1 = 255.0
        rgb2 = 0
        img_out = rgb1 * mask_1 + rgb2 * (1 - mask_1)
    
    # 增量大于0小于1
    elif contrast >= 0 :
        alpha = 1 - contrast
        alpha = 1/alpha - 1
        img_out[:, :, 0] = img[:, :, 0] + (img[:, :, 0] - threshold * 255.0) * alpha
        img_out[:, :, 1] = img[:, :, 1] + (img[:, :, 1] - threshold * 255.0) * alpha
        img_out[:, :, 2] = img[:, :, 2] + (img[:, :, 2] - threshold * 255.0) * alpha
        
    # 增量小于0
    else:
        alpha = contrast
        img_out[:, :, 0] = img[:, :, 0] + (img[:, :, 0] - threshold * 255.0) * alpha
        img_out[:, :, 1] = img[:, :, 1] + (img[:, :, 1] - threshold * 255.0) * alpha
        img_out[:, :, 2] = img[:, :, 2] + (img[:, :, 2] - threshold * 255.0) * alpha
    
    img_out = img_out/255.0
    return img_out

path = './resource/fruit.bmp'
contrast = 0.5   # 范围:-1至1
threshold = 0.5   # 范围:0至1

#  run : python Contrast.py (path) (contrast) (threshold)
if __name__ == "__main__":
    len = len(sys.argv)
    if len >= 2 :
        path = sys.argv[1]
        if len >= 3 :
            contrast = float(sys.argv[2])
            if len >= 4 :
                threshold = float(sys.argv[3])

    img = cv2.imread(path)
    img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
    img_new = ContrastAlgorithm(img, contrast, threshold)

    plt.figure("img_original")
    plt.imshow(img/255.0)
    plt.axis('off')

    plt.figure("img_contrast")
    plt.imshow(img_new)
    plt.axis('off')

    plt.show() 



版权声明:本文为Benja_K原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。