opencv 自动gamma矫正
时间: 2023-07-30 22:12:59 浏览: 55
OpenCV中可以通过对图像进行Gamma矫正来增强图像的对比度和亮度,从而改善图像的视觉效果。Gamma矫正是一种非线性操作,它可以通过对每个像素进行指数变换来实现。具体步骤如下:
1. 读取图像并转换为灰度图像。
```python
import cv2
import numpy as np
img = cv2.imread('input.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
2. 计算Gamma值。
```python
gamma = 0.5
```
3. 对灰度图像进行Gamma矫正。
```python
invGamma = 1.0 / gamma
table = np.array([((i / 255.0) ** invGamma) * 255 for i in np.arange(0, 256)]).astype("uint8")
result = cv2.LUT(gray, table)
```
其中,invGamma为Gamma值的倒数,table为Gamma变换的LUT表,result即为矫正后的图像。
4. 显示结果。
```python
cv2.imshow('original', gray)
cv2.imshow('gamma corrected', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这样就可以使用OpenCV实现自动Gamma矫正了。
相关问题
opencv 自动gamma矫正c++代码
下面是使用C++实现自动Gamma矫正的OpenCV代码:
```c++
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
Mat img = imread("input.jpg");
Mat gray;
cvtColor(img, gray, COLOR_BGR2GRAY);
double gamma = 0.5;
double invGamma = 1.0 / gamma;
Mat table(1, 256, CV_8U);
uchar* p = table.ptr();
for (int i = 0; i < 256; i++)
{
p[i] = static_cast<uchar>(pow(i / 255.0, invGamma) * 255.0);
}
Mat result;
LUT(gray, table, result);
imshow("original", gray);
imshow("gamma corrected", result);
waitKey(0);
destroyAllWindows();
return 0;
}
```
这段代码与Python实现类似,只是语法稍有不同。需要注意的是,在C++中需要使用pow函数进行指数计算,而在Python中可以直接使用**操作符。另外,由于C++不支持numpy数组,因此需要使用Mat来存储和操作图像。
opencv 对彩色图自动gamma矫正c++代码
以下是使用 OpenCV 对彩色图像进行自动 Gamma 矫正的 C++ 代码:
```cpp
#include <opencv2/opencv.hpp>
#include <cmath>
using namespace cv;
Mat gamma_correction(Mat& src, float gamma) {
Mat lut_matrix(1, 256, CV_8UC1);
uchar* ptr = lut_matrix.ptr();
float inv_gamma = 1.0 / gamma;
for (int i = 0; i < 256; i++) {
ptr[i] = (int)(pow((float)i / 255.0, inv_gamma) * 255.0);
}
Mat dst;
LUT(src, lut_matrix, dst);
return dst;
}
int main() {
Mat img = imread("input.jpg");
Mat img_gamma_corrected = gamma_correction(img, 1.5); // gamma value can be adjusted
imshow("Original Image", img);
imshow("Gamma Corrected Image", img_gamma_corrected);
waitKey();
return 0;
}
```
这段代码使用了 OpenCV 的 LUT(查找表)函数,通过计算 Gamma 校正函数的查找表,然后使用 LUT 函数对图像进行 Gamma 校正。Gamma 值可以根据实际情况进行调整。