<p>这里有一个非常数学和直接的方法来调整亮度和对比度作为参数。对比度控制输出值与输入值绘图中直线方程的斜率。截距取决于亮度和对比度。亮度控制直线坡度的轴点,以便所需结果越亮,轴点越高。这里的代码提供了bri和con参数,这些参数可以在-100到100范围内更改,但是限制了这样就不能反转对比度。值bri=0和con=-100将使图像饱和度降低,使其完全处于中灰色。值bri=100和con=-100将生成纯白色图像。同样,bri=-100和con=-100将生成纯黑色图像。所以bri和con的值就像百分比变化。因此,bri=0和con=0与输入没有变化。在</p>
<p>输入:</p>
<p><a href="https://i.stack.imgur.com/EvTzu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EvTzu.png" alt="enter image description here"/></a></p>
<pre><code>import cv2
import numpy as np
import math
# load image with alpha channel
img = cv2.imread('lena.png')
# define desired brightness and contrast change values
bri = 20
con = 20
# compute slope and intercept
diffcon = (100 - con)
if diffcon <= 0.1: con=99.9
arg = math.pi * (((con * con) / 20000) + (3 * con / 200)) / 4
slope = 1 + (math.sin(arg) / math.cos(arg))
if slope < 0: slope=0
pivot = (100 - bri) / 200
intcpbri = bri / 100
intcpcon = pivot * (1 - slope)
intercept = (intcpbri + intcpcon)
# print slope and intercept
print(slope, intercept)
# apply slope and intercept
img = img/255.0
out = slope * img + intercept
out[out>1] = 1
out[out<0] = 0
# display IN and OUT images
cv2.imshow('IN', img)
cv2.imshow('OUT', out)
cv2.waitKey(0)
cv2.destroyAllWindows()
# save output image
out = 255.0 * out
out = out.astype(int)
cv2.imwrite('lena_bc_20_20.png', out)
</code></pre>
<p><br/>
<a href="https://i.stack.imgur.com/rvIX8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rvIX8.png" alt="enter image description here"/></a></p>