Skip to main content
 首页 » 编程设计

python之纯粹用numpy调整图像的对比度

2025年05月04日11leader

我正在尝试为灰度颜色的图像编写对比度调整,但到目前为止找不到正确的方法。这是我想出的:

import numpy as np 
import matplotlib.pyplot as plt 
from PIL import Image 
from scipy import misc 
def fix_contrast(image): 
    minimumColor = np.amin(image) 
    maximumColor = np.amax(image) 
    #avg = (minimumColor - maximumColor)/2 first attempt 
    avg = np.mean(image) #second attempt 
    colorDownMatrix = image < avg # also tried 
    colorUpMatrix = image > avg  
    #also tried:   colorUpMatrix = image > avg * 1.2 
    # and : colorDownMatrix = image < avg* 0.3 
 
    image = image - minimumColor*colorDownMatrix 
    image = image + maximumColor*colorUpMatrix 
    lessThen0 = image<0 
    moreThen255 = image>255 
    image[lessThen0] = 0 
    image[moreThen255] = 255 
    return image     

我的一般尝试是将元素减少到 0,即它们“更接近”到 0 的像素,并将元素增加到 255,即“更接近”到 255 的元素。我尝试通过平均函数来测量接近度,但在此之前通过算术平均值,但我所有的尝试都没有得到任何好的结果。

我正在处理的图像:

我想要的结果:

我是否接近解决方案?任何提示/技巧都会很棒

请您参考如下方法:

我正在学习 Python 和 numpy,并认为我会尝试实现一个“查找表” (LUT)。它有效,输出图像具有从黑色到白色的完整范围,但我很高兴收到改进建议。

#!/usr/local/bin/python3 
import numpy as np 
from PIL import Image 
 
# Open the input image as numpy array, convert to greyscale and drop alpha 
npImage=np.array(Image.open("cartoon.png").convert("L")) 
 
# Get brightness range - i.e. darkest and lightest pixels 
min=np.min(npImage)        # result=144 
max=np.max(npImage)        # result=216 
 
# Make a LUT (Look-Up Table) to translate image values 
LUT=np.zeros(256,dtype=np.uint8) 
LUT[min:max+1]=np.linspace(start=0,stop=255,num=(max-min)+1,endpoint=True,dtype=np.uint8) 
 
# Apply LUT and save resulting image 
Image.fromarray(LUT[npImage]).save('result.png')