adjust the contrast of image brightness opencv

Image Processing

Image conversion is to find a function, the function of the original image matrix after treatment, converted to the target image matrix  
can be divided into two ways, i.e., transformation and regional levels of pixel-level transform

  • Point operators (pixel transforms)
  • Neighborhood (area-based) operators

Converting pixel level equivalent \ (P_ After} {(I, J) = F ({before} P_ (I, J)) \) , i.e., each pixel value after conversion are the same position before conversion pixel values are a function mapping relationship.

Contrast and brightness change

Linear transformation  

The most commonly used is a linear transformation. That \ (G (I, J) = \ Alpha \ CDOT F (I, J) + \ Beta \)
F (I, J) is the original pixel value, g (i, j) is the pixel value after conversion.
\ (\ Alpha \) to adjust the contrast, \ (\ Beta \) to adjust the brightness. sometimes referred to as bias and gain parameters.

What a contrast? Not that "the difference between light and dark" do? That is the difference between the size of the pixel values. I multiplied by a factor alpha, alpha time is large when the difference in brightness amplification values, i.e. increased contrast, when the alpha is small, the difference in brightness is reduced, the contrast is reduced.

beta better understanding, plus a number directly on the luminance values ​​of pixels, a positive number is to increase the brightness, a negative number to decrease the brightness.

Looking at the example of the following code:

from __future__ import print_function
from builtins import input
import cv2 as cv
import numpy as np
import argparse
# Read image given by user
parser = argparse.ArgumentParser(description='Code for Changing the contrast and brightness of an image! tutorial.')
parser.add_argument('--input', help='Path to input image.', default='lena.jpg')
args = parser.parse_args()
image = cv.imread(cv.samples.findFile(args.input))
if image is None:
    print('Could not open or find the image: ', args.input)
    exit(0)
new_image = np.zeros(image.shape, image.dtype)
alpha = 1.0 # Simple contrast control
beta = 0    # Simple brightness control
# Initialize values
print(' Basic Linear Transforms ')
print('-------------------------')
try:
    alpha = float(input('* Enter the alpha value [1.0-3.0]: '))
    beta = int(input('* Enter the beta value [0-100]: '))
except ValueError:
    print('Error, not a number')
# Do the operation new_image(i,j) = alpha*image(i,j) + beta
# Instead of these 'for' loops we could have used simply:
# new_image = cv.convertScaleAbs(image, alpha=alpha, beta=beta)
# but we wanted to show you how to access the pixels :)
for y in range(image.shape[0]):
    for x in range(image.shape[1]):
        for c in range(image.shape[2]):
            new_image[y,x,c] = np.clip(alpha*image[y,x,c] + beta, 0, 255)
cv.imshow('Original Image', image)
cv.imshow('New Image', new_image)
# Wait until user press some key
cv.waitKey()

Tip module 'cv2' has no attribute 'samples', then the first installation pip install opencv-python == 4.0.0.21.

Execute: python change_brightness_contrast.py --input ./lights.jpeg

The figure is alpha = 2, beta = 20, a renderings.

Nonlinear transformation

Linear transformation there is a problem, as shown above, α = 1.3 and β = 40, the original image brightness while improving, leading to a barely visible cloud. If you want to see if the cloud, building and enough brightness.

This time the introduction of non-linear transformation. Correction called the Gamma
\ (= O \ left (\ FRAC the I {255} {} \ right) ^ {\ Gamma} \ Times 255 \)
with different linear transformation, different original luminance value, which is different from the intensity change is nonlinear.

When the γ <1, the picture brightness increases. > 1, reducing the brightness.

γ = 0.4 the effect of the change described above in FIG. clouds and construction can be seen brightened while maintaining the contrast of the image so that still clear.


If you look at different gradation conversion can be seen if the histogram. The histogram middle picture can be seen a lot of low luminance pixel values.
Left is made a linear transformation of the right overall histogram generation shift, and the peak at 255. since each pixel are increased brightness thing. clouds resulted in blue too bright and indistinguishable.
and the right image brightness made more uniform distribution of gamma correction, even if the part to be low luminance values strengthened, but not so overexposed makes the clouds indistinguishable.

Gamma correction code implementation follows.

    lookUpTable = np.empty((1,256), np.uint8)
    for i in range(256):
        lookUpTable[0,i] = np.clip(pow(i / 255.0, gamma) * 255.0, 0, 255)
    res = cv.LUT(img_original, lookUpTable)

Cv.LUT which is a transformation function. LookUpTable found transform the relationship from the inside, to generate a new image matrix. Https://docs.opencv.org/master/d2/de8/group__core__array.html#gab55b8d062b7f5587720ede032d34156f

Reference: https://docs.opencv.org/master/d3/dc1/tutorial_basic_linear_transform.html

Guess you like

Origin www.cnblogs.com/sdu20112013/p/11597171.html