📜  使用Python更改图像的对比度和亮度 – OpenCV

📅  最后修改于: 2022-05-13 01:55:31.461000             🧑  作者: Mango

使用Python更改图像的对比度和亮度 – OpenCV

更改任何图像的亮度和对比度级别是每个人对图像所做的最基本的事情。它旨在更改图像的每个像素的值,可以通过乘以或除以图像的像素值来完成。在本文中,我们将看到如何使用 OpenCV Python以优美的代码实现我们的理论,

在开始之前,让我们尝试了解一些基本概念,例如,什么是亮度?什么是对比?什么是像素?什么是 OpenCV?

  • 亮度:调整亮度时,图像内的整个色调范围会相应地升高或降低。
  • 对比度:提高对比度时,消除中间色调。图像将具有更高百分比的暗部或黑白或高光,中间色调最少。
  • 像素:像素通常用于指计算机显示器或屏幕的显示分辨率。像素越大,图像中的细节就越多。
  • OpenCV: OpenCV 是用于计算机视觉、机器学习和图像处理的巨大开源库,现在它在实时操作中发挥着重要作用

议程:学习如何使用 OpenCV 调整图像的亮度和对比度。

要求: OpenCV

安装:

pip install openCV

方法:

  • 导入所需的模块。
  • 定义主函数,在其中定义需要的数据。
  • 创建一个函数brightness_contrast,创建一个轨迹条来调整亮度和对比度。
  • 创建另一个函数来更改亮度和对比度。
  • 显示原始图像和编辑后的图像。
  • 使用“ESC”终止程序或直接关闭窗口。

让我们逐步实现这一点:

第 1 步:这里 我们将加载一个图像并创建一个轨迹栏。

代码:

Python3
if __name__ == '__main__':
    # The function imread loads an 
    # image from the specified file and returns it.
    original = cv2.imread("pic.jpeg")
  
    # Making another copy of an image.
    img = original.copy()
  
    # The function namedWindow creates
    # a window that can be used as 
    # a placeholder for images.
    cv2.namedWindow('GEEK')
  
    # The function imshow displays 
    # an image in the specified window.
    cv2.imshow('GEEK', original)
  
    # createTrackbar(trackbarName, 
    # windowName, value, count, onChange)
    # Brightness range -255 to 255
    cv2.createTrackbar('Brightness', 'GEEK',
                       255, 2 * 255,
                       BrightnessContrast) 
      
    # Contrast range -127 to 127
    cv2.createTrackbar('Contrast', 'GEEK',
                       127, 2 * 127,
                       BrightnessContrast)  
      
    BrightnessContrast(0)
  
# The function waitKey waits for 
# a key event infinitely  or for
# delay milliseconds, when it is positive.
cv2.waitKey(0)


Python3
def BrightnessContrast(brightness=0):
  
    # getTrackbarPos returns the 
    # current position of the specified trackbar.
    brightness = cv2.getTrackbarPos('Brightness',
                                    'GEEK')
      
    contrast = cv2.getTrackbarPos('Contrast',
                                  'GEEK')
      
    effect = controller(img,
                        brightness,
                        contrast)
  
    # The function imshow displays 
    # an image in the specified window
    cv2.imshow('Effect', effect)


Python3
def controller(img, brightness=255, contrast=127):
    brightness = int((brightness - 0) * (255 - (-255)) / (510 - 0) + (-255))
  
    contrast = int((contrast - 0) * (127 - (-127)) / (254 - 0) + (-127))
  
    if brightness != 0:
  
        if brightness > 0:
  
            shadow = brightness
  
            max = 255
  
        else:
  
            shadow = 0
            max = 255 + brightness
  
        al_pha = (max - shadow) / 255
        ga_mma = shadow
  
        # The function addWeighted 
        # calculates the weighted sum 
        # of two arrays
        cal = cv2.addWeighted(img, al_pha,
                              img, 0, ga_mma)
  
    else:
        cal = img
  
    if contrast != 0:
        Alpha = float(131 * (contrast + 127)) / (127 * (131 - contrast))
        Gamma = 127 * (1 - Alpha)
  
        # The function addWeighted calculates
        # the weighted sum of two arrays
        cal = cv2.addWeighted(cal, Alpha,
                              cal, 0, Gamma)
  
    # putText renders the specified
    # text string in the image.
    cv2.putText(cal, 'B:{},C:{}'.format(brightness, 
                                        contrast), 
                (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 
                1, (0, 0, 255), 2)
  
    return cal


Python3
import cv2
  
def BrightnessContrast(brightness=0):
     
    # getTrackbarPos returns the current
    # position of the specified trackbar.
    brightness = cv2.getTrackbarPos('Brightness',
                                    'GEEK')
      
    contrast = cv2.getTrackbarPos('Contrast',
                                  'GEEK')
  
    effect = controller(img, brightness, 
                        contrast)
  
    # The function imshow displays an image
    # in the specified window
    cv2.imshow('Effect', effect)
  
def controller(img, brightness=255,
               contrast=127):
    
    brightness = int((brightness - 0) * (255 - (-255)) / (510 - 0) + (-255))
  
    contrast = int((contrast - 0) * (127 - (-127)) / (254 - 0) + (-127))
  
    if brightness != 0:
  
        if brightness > 0:
  
            shadow = brightness
  
            max = 255
  
        else:
  
            shadow = 0
            max = 255 + brightness
  
        al_pha = (max - shadow) / 255
        ga_mma = shadow
  
        # The function addWeighted calculates
        # the weighted sum of two arrays
        cal = cv2.addWeighted(img, al_pha, 
                              img, 0, ga_mma)
  
    else:
        cal = img
  
    if contrast != 0:
        Alpha = float(131 * (contrast + 127)) / (127 * (131 - contrast))
        Gamma = 127 * (1 - Alpha)
  
        # The function addWeighted calculates
        # the weighted sum of two arrays
        cal = cv2.addWeighted(cal, Alpha, 
                              cal, 0, Gamma)
  
    # putText renders the specified text string in the image.
    cv2.putText(cal, 'B:{},C:{}'.format(brightness,
                                        contrast), (10, 30),
                cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
  
    return cal
  
if __name__ == '__main__':
    # The function imread loads an image
    # from the specified file and returns it.
    original = cv2.imread("pic.jpeg")
  
    # Making another copy of an image.
    img = original.copy()
  
    # The function namedWindow creates a
    # window that can be used as a placeholder
    # for images.
    cv2.namedWindow('GEEK')
  
    # The function imshow displays an 
    # image in the specified window.
    cv2.imshow('GEEK', original)
  
    # createTrackbar(trackbarName, 
    # windowName, value, count, onChange)
     # Brightness range -255 to 255
    cv2.createTrackbar('Brightness',
                       'GEEK', 255, 2 * 255,
                       BrightnessContrast) 
      
    # Contrast range -127 to 127
    cv2.createTrackbar('Contrast', 'GEEK',
                       127, 2 * 127,
                       BrightnessContrast)  
  
      
    BrightnessContrast(0)
  
# The function waitKey waits for 
# a key event infinitely  or for delay 
# milliseconds, when it is positive.
cv2.waitKey(0)


步骤 2:通过调用控制器函数,它将返回编辑后的图像,然后 imshow()函数将显示受影响的图像。

代码:

蟒蛇3

def BrightnessContrast(brightness=0):
  
    # getTrackbarPos returns the 
    # current position of the specified trackbar.
    brightness = cv2.getTrackbarPos('Brightness',
                                    'GEEK')
      
    contrast = cv2.getTrackbarPos('Contrast',
                                  'GEEK')
      
    effect = controller(img,
                        brightness,
                        contrast)
  
    # The function imshow displays 
    # an image in the specified window
    cv2.imshow('Effect', effect)

第三步:控制器函数会根据轨迹栏位置控制图像的亮度和对比度,并返回编辑后的图像。

蟒蛇3

def controller(img, brightness=255, contrast=127):
    brightness = int((brightness - 0) * (255 - (-255)) / (510 - 0) + (-255))
  
    contrast = int((contrast - 0) * (127 - (-127)) / (254 - 0) + (-127))
  
    if brightness != 0:
  
        if brightness > 0:
  
            shadow = brightness
  
            max = 255
  
        else:
  
            shadow = 0
            max = 255 + brightness
  
        al_pha = (max - shadow) / 255
        ga_mma = shadow
  
        # The function addWeighted 
        # calculates the weighted sum 
        # of two arrays
        cal = cv2.addWeighted(img, al_pha,
                              img, 0, ga_mma)
  
    else:
        cal = img
  
    if contrast != 0:
        Alpha = float(131 * (contrast + 127)) / (127 * (131 - contrast))
        Gamma = 127 * (1 - Alpha)
  
        # The function addWeighted calculates
        # the weighted sum of two arrays
        cal = cv2.addWeighted(cal, Alpha,
                              cal, 0, Gamma)
  
    # putText renders the specified
    # text string in the image.
    cv2.putText(cal, 'B:{},C:{}'.format(brightness, 
                                        contrast), 
                (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 
                1, (0, 0, 255), 2)
  
    return cal

以下是完整的实现:

蟒蛇3

import cv2
  
def BrightnessContrast(brightness=0):
     
    # getTrackbarPos returns the current
    # position of the specified trackbar.
    brightness = cv2.getTrackbarPos('Brightness',
                                    'GEEK')
      
    contrast = cv2.getTrackbarPos('Contrast',
                                  'GEEK')
  
    effect = controller(img, brightness, 
                        contrast)
  
    # The function imshow displays an image
    # in the specified window
    cv2.imshow('Effect', effect)
  
def controller(img, brightness=255,
               contrast=127):
    
    brightness = int((brightness - 0) * (255 - (-255)) / (510 - 0) + (-255))
  
    contrast = int((contrast - 0) * (127 - (-127)) / (254 - 0) + (-127))
  
    if brightness != 0:
  
        if brightness > 0:
  
            shadow = brightness
  
            max = 255
  
        else:
  
            shadow = 0
            max = 255 + brightness
  
        al_pha = (max - shadow) / 255
        ga_mma = shadow
  
        # The function addWeighted calculates
        # the weighted sum of two arrays
        cal = cv2.addWeighted(img, al_pha, 
                              img, 0, ga_mma)
  
    else:
        cal = img
  
    if contrast != 0:
        Alpha = float(131 * (contrast + 127)) / (127 * (131 - contrast))
        Gamma = 127 * (1 - Alpha)
  
        # The function addWeighted calculates
        # the weighted sum of two arrays
        cal = cv2.addWeighted(cal, Alpha, 
                              cal, 0, Gamma)
  
    # putText renders the specified text string in the image.
    cv2.putText(cal, 'B:{},C:{}'.format(brightness,
                                        contrast), (10, 30),
                cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
  
    return cal
  
if __name__ == '__main__':
    # The function imread loads an image
    # from the specified file and returns it.
    original = cv2.imread("pic.jpeg")
  
    # Making another copy of an image.
    img = original.copy()
  
    # The function namedWindow creates a
    # window that can be used as a placeholder
    # for images.
    cv2.namedWindow('GEEK')
  
    # The function imshow displays an 
    # image in the specified window.
    cv2.imshow('GEEK', original)
  
    # createTrackbar(trackbarName, 
    # windowName, value, count, onChange)
     # Brightness range -255 to 255
    cv2.createTrackbar('Brightness',
                       'GEEK', 255, 2 * 255,
                       BrightnessContrast) 
      
    # Contrast range -127 to 127
    cv2.createTrackbar('Contrast', 'GEEK',
                       127, 2 * 127,
                       BrightnessContrast)  
  
      
    BrightnessContrast(0)
  
# The function waitKey waits for 
# a key event infinitely  or for delay 
# milliseconds, when it is positive.
cv2.waitKey(0)

输出: