python - 我想以动态方式增加图像的亮度和对比度,以便该程序适用于任何新图像

标签 python opencv image-processing brightness contrast

我需要以动态方式增加或减少图像的对比度和亮度以使其清晰可见的图像很少。并且该程序需要是动态的,以便它甚至也适用于新图像。我也希望角色应该是黑暗的。

我能够增加亮度和对比度,但它对每张图片都不起作用。

import cv2

import numpy as np

img = cv2.imread('D:\Bright.png')

image = cv2.GaussianBlur(img, (5, 5), 0)

#image = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY)[1]

#kernel = np.ones((2,1),np.uint8)

#dilation = cv2.dilate(img,kernel)

cv2.imshow('test', image)

cv2.waitKey(0)

cv2.destroyAllWindows()

imghsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)


imghsv[:,:,2] = [[max(pixel - 25, 0) if pixel < 190 else min(pixel + 25, 255) for pixel in row] for row in imghsv[:,:,2]]

cv2.imshow('contrast', cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR))

#cv2.imwrite('D:\\112.png',cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR))

cv2.waitKey(0)

cv2.destroyAllWindows()

#raw_input()

我想要一个程序,它可以很好地处理每张图片,并且文字颜色稍微深一点,这样它们就很容易看到。

image 1

image 2

image 3

最佳答案

正如 Tilarion 所建议的,您可以尝试“自动亮度和对比度”,看看它是否有效。这背后的理论解释得很好here在解决方案部分。解决方案是在 C++ 中。我已经用 Python 编写了一个版本,您可以直接使用它,一次只能在一个 channel 上使用彩色图像:

def auto_brightandcontrast(input_img, channel, clip_percent=1):
    histSize=180
    alpha=0
    beta=0
    minGray=0
    maxGray=0
    accumulator=[]

    if(clip_percent==0):
        #min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(hist)
        return input_img

    else:
        hist = cv2.calcHist([input_img],[channel],None,[256],[0, 256])
        accumulator.insert(0,hist[0])    

        for i in range(1,histSize):
            accumulator.insert(i,accumulator[i-1]+hist[i])

        maxx=accumulator[histSize-1]
        minGray=0

        clip_percent=clip_percent*(maxx/100.0)
        clip_percent=clip_percent/2.0

        while(accumulator[minGray]<clip_percent[0]):
            minGray=minGray+1

        maxGray=histSize-1
        while(accumulator[maxGray]>=(maxx-clip_percent[0])):
            maxGray=maxGray-1

        inputRange=maxGray-minGray

        alpha=(histSize-1)/inputRange
        beta=-minGray*alpha

        out_img=input_img.copy()

        cv2.convertScaleAbs(input_img,out_img,alpha,beta)

        return out_img

关于python - 我想以动态方式增加图像的亮度和对比度,以便该程序适用于任何新图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56388949/

相关文章:

android - sl4a python 为安卓手机做一个Toast

python - 将 find 输出作为参数传递时出现 "Argument list too long"错误

python - keras 顺序模型中的输入形状错误

python - YUV420p转其他格式,色偏问题

由于存在 'Not well-formed xml' 个字符,Python 给出 '&' 错误

python - 如何从图像中删除水平和垂直线

opengl - 增强现实OpenGL+OpenCV

c++ - OpenCV 项目无法编译

python - 识别模板图像中的矩形

c++ - 访问 cvCreateMatND 的元素