Linear transformation of gray value

principle

Assuming that the input image is I, the width is W, the height is H, and the output image is denoted as O, the linear transformation of the image can be defined by the following formula:

\(O(r,c) = a*I(r,c) + b, 0 \leq r< H, 0 \leq c < W\)
When a=1, b=0, O is a copy of I; if a>1, the contrast ratio of the output image O is increased compared to I; If a<1, the contrast ratio of O is reduced than that of I. The change of the b value affects the brightness of the output image. When b>0, the brightness increases; when b<0, the brightness decreases.

code

# !/usr/bin/env python
# -*-encoding: utf-8-*-
# author:LiYanwei
# version:0.1


import cv2
import numpy as np

if __name__ =="__main__":
    image = cv2.imread('img1.jpg', cv2.IMREAD_GRAYSCALE)
    MAX_VALUE = 120
    value = 120

    #调整对比度后,图像的效果显示窗口
    cv2.namedWindow("contrast",cv2.WND_PROP_AUTOSIZE)

    #调整系数,观察图像的变化
    def callback_contrast(_value):
        #通过线性运算,调整图像对比度
        a = float(_value)/40.0
        contrastImage = a*image
        contrastImage[contrastImage > 255] = 255
        contrastImage = np.round(contrastImage)
        contrastImage = contrastImage.astype(np.uint8)
        cv2.imshow("contrast", contrastImage)
        cv2.imwrite("contrast.jpg", contrastImage)

    callback_contrast(value)
    cv2.createTrackbar("value", "contrast", value, MAX_VALUE, callback_contrast)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324749246&siteId=291194637