opencv 调整图像亮度对比度

图像处理
图像变换就是找到一个函数,把原始图像矩阵经过函数处理后,转换为目标图像矩阵.  
可以分为两种方式,即像素级别的变换和区域级别的变换

Point operators (pixel transforms)
Neighborhood (area-based) operators
像素级别的变换就相当于pafter(i,j)=f(pbefore(i,j)),即变换后的每个像素值都与变换前的同位置的像素值有个函数映射关系.

对比度和亮度改变 线性变换
最常用的是线性变换.即
g(i,j)=α⋅f(i,j)+β

f(i,j)是原像素值,g(i,j)是变换后的像素值.
α调整对比度,
β调整亮度.有时也称之为gain和bias参数.

对比度是什么?不就是"亮和暗的区别"吗?也就是像素值的大小的区别.那我乘以一个alpha系数,当alpha很大的时候就是放大了这种亮度值的差异,也就是提高了对比度,当alpha很小时,也就是缩小了亮度的差异,也就是缩小了对比度.

beta就更好理解了,直接在像素的亮度值上加上一个数,正数就是提高亮度,负数降低亮度.

看一下下面代码的示例:

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()

提示module ‘cv2’ has no attribute 'samples’的话要先安装pip install opencv-python==4.0.0.21.

执行:python change_brightness_contrast.py --input ./lights.jpeg

在这里插入图片描述

上图是alpha=2,beta=20的一个效果图.

非线性变换
在这里插入图片描述

线性变换有个问题,如上图,α=1.3 and β=40,提高原图亮度的同时,导致云几乎看不见了.如果要看见云的话,建筑的亮度又不够.

这个时候就引入了非线性变换. 称之为Gamma correction
O=(I/255)γ×255

与线性变换不同,对不同的原始亮度值,其改变强度是不同的,是非线性的.
在这里插入图片描述

在 γ<1的时候,会提高图片亮度.>1时,降低亮度.
在这里插入图片描述

γ=0.4的变换效果图如上.可以看到云层及建筑变亮的同时还保持了对比度让图像依然清晰.

在这里插入图片描述

如果查看不同变换下的灰度直方图的话可以看到.中间是原图的灰度直方图,可以看到低亮度值的像素点很多.
左边是做了线性变换的,整体直方图产生了右移,并且在255处出现峰值.因为每个像素点都增加了亮度嘛.导致了白云和蓝天过于明亮无法区分.
而右边做了gamma校正的图像亮度分布比较均匀,即使得低亮度值的部分得以加强,又不至于过度曝光使得白云无法区分.

实现Gamma correction的代码如下.

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就是个变换函数.从lookUpTable里找到变换关系,生成新的图像矩阵.https://docs.opencv.org/master/d2/de8/group__core__array.html#gab55b8d062b7f5587720ede032d34156f

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

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C++中,可以使用OpenCV库来实现图像亮度对比度和伽马值调整。下面是一个简单的示例代码: ```cpp #include <opencv2/opencv.hpp> #include <iostream> using namespace cv; // 亮度对比度调整函数 void adjustBrightnessContrast(Mat& image, double alpha, int beta) { // 遍历图像的每个像素 for (int y = 0; y < image.rows; y++) { for (int x = 0; x < image.cols; x++) { for (int c = 0; c < image.channels(); c++) { // 对每个通道的像素进行亮度对比度调整 image.at<Vec3b>(y, x)[c] = saturate_cast<uchar>(alpha * image.at<Vec3b>(y, x)[c] + beta); } } } } // 伽马值调整函数 void adjustGamma(Mat& image, double gamma) { // 建立查找表 unsigned char lut[256]; for (int i = 0; i < 256; i++) { lut[i] = saturate_cast<uchar>(pow((double)i / 255.0, gamma) * 255.0); } // 应用查找表 image = image.clone(); LUT(image, Mat(1, 256, CV_8UC1, lut), image); } int main() { // 读取图像 Mat image = imread("input.jpg"); if (image.empty()) { std::cerr << "Failed to read image." << std::endl; return -1; } // 调整亮度对比度 double alpha = 1.5; // 亮度调整参数 int beta = 30; // 对比度调整参数 adjustBrightnessContrast(image, alpha, beta); // 调整伽马值 double gamma = 1.5; // 伽马值调整参数 adjustGamma(image, gamma); // 显示结果图像 imshow("Adjusted Image", image); waitKey(0); return 0; } ``` 在这个示例代码中,我们首先定义了两个函数:`adjustBrightnessContrast`和`adjustGamma`,分别用于亮度对比度、伽马值的调整。然后在`main`函数中,我们读取了一张图像,然后分别调用这两个函数进行图像处理。最后,将处理后的图像显示出来。 请确保在编译和运行代码之前,已经安装了OpenCV库,并将示例代码中的`input.jpg`替换为你自己的图像路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值