Python OpenCV cv2 - 对图片进行100%亮度和对比度简单增强的方法

2024-07-05 14:35:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想改变现有图像的亮度和对比度100%。在

decoded = Image.open(BytesIO(base64.b64decode(base64Data)))
image = cv2.cvtColor(np.array(decoded), cv2.COLOR_BGR2RGB)

有什么功能可以让我这么做吗?在


Tags: 图像imagenpopenarraycv2colordecoded
3条回答

这里有一个简单的方法,使用脱脂重缩放强度。您提供要成为min=0和max=255输出值的最小和最大输入值,它对所有图像值进行线性调整。这里有两个例子:

输入:

enter image description here

import cv2
import numpy as np
import skimage.exposure

# load image with alpha channel
img = cv2.imread('lena.png')

# adjust just the input max value   
out1 = skimage.exposure.rescale_intensity(img, in_range=(0,128), out_range=(0,255))
cv2.imwrite('lena_stretch_0_128.png', out1)

 # adjust both the input min and max values   
out2 = skimage.exposure.rescale_intensity(img, in_range=(64,192), out_range=(0,255))
cv2.imwrite('lena_stretch_64_192.png', out2)

cv2.imshow('Out1', out1)
cv2.imshow('Out2', out2)
cv2.waitKey(0)
cv2.destroyAllWindows()


输出1(仅调整输入最小值):

enter image description here

输出2(同时调整输入最小值和最大值):

enter image description here

我找不到OpenCV函数,但我找到了指南: https://docs.opencv.org/3.4/d3/dc1/tutorial_basic_linear_transform.html 它说你可以这样调节对比度和亮度:

new_image = old_image * contrast_coeff + brightness_coeff

但是,我没有使用它,因为你可以注意到,如果你只想改变对比度,它不会同时使暗像素变暗而亮像素变亮。在

之前我使用了tensorflow的对比度调整,所以我使用它的公式:

^{pr2}$

另外,您可能希望将结果转换为int,所以最好将小于0和大于1的值截断。您可以将其规格化,也可以只剪辑:

new_image = np.clip(new_image, a_min=0., a_max=1.)     # cut values under 0 and over 1 

如您所见,所有这些都不是使用OpenCV,而是使用NumPy,所以我希望它适合您的需要。在

你也可以在那里读到不同的对比度公式:https://en.wikipedia.org/wiki/Contrast_(vision)

这里有一个非常数学和直接的方法来调整亮度和对比度作为参数。对比度控制输出值与输入值绘图中直线方程的斜率。截距取决于亮度和对比度。亮度控制直线坡度的轴点,以便所需结果越亮,轴点越高。这里的代码提供了bri和con参数,这些参数可以在-100到100范围内更改,但是限制了这样就不能反转对比度。值bri=0和con=-100将使图像饱和度降低,使其完全处于中灰色。值bri=100和con=-100将生成纯白色图像。同样,bri=-100和con=-100将生成纯黑色图像。所以bri和con的值就像百分比变化。因此,bri=0和con=0与输入没有变化。在

输入:

enter image description here

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)


enter image description here

相关问题 更多 >