用opencv和C++实现图片的对比度亮度和伽马值调节
时间: 2023-06-10 12:06:36 浏览: 151
opencv 实现 Photoshop 亮度 对比度 调节功能
要使用OpenCV和C来实现图片的对比度、亮度和伽马值调节,可以按照以下步骤进行:
1. 加载图片
使用OpenCV中的cvLoadImage函数来加载图片,例如:
```c
IplImage* img = cvLoadImage("image.jpg", CV_LOAD_IMAGE_COLOR);
```
2. 调整亮度
亮度可以通过修改图像中所有像素的像素值来实现。可以使用以下代码来增加或减少亮度:
```c
int brightness = 50; // 亮度增加值
for (int i = 0; i < img->height; i++) {
for (int j = 0; j < img->width; j++) {
for (int k = 0; k < img->nChannels; k++) {
uchar* pixel = &((uchar*)(img->imageData + img->widthStep*i))[j*img->nChannels + k];
int value = *pixel + brightness;
*pixel = (value > 255) ? 255 : (uchar)value;
}
}
}
```
3. 调整对比度
对比度可以通过修改图像中的像素值范围来实现。可以使用以下代码来增加或减少对比度:
```c
float contrast = 1.5; // 对比度增加值
for (int i = 0; i < img->height; i++) {
for (int j = 0; j < img->width; j++) {
for (int k = 0; k < img->nChannels; k++) {
uchar* pixel = &((uchar*)(img->imageData + img->widthStep*i))[j*img->nChannels + k];
int value = (int)(*pixel - 128) * contrast + 128;
*pixel = (value > 255) ? 255 : ((value < 0) ? 0 : (uchar)value);
}
}
}
```
4. 调整伽马值
伽马值可以通过将图像中的像素值进行幂运算来实现。可以使用以下代码来调整伽马值:
```c
float gamma = 0.5; // 伽马值
for (int i = 0; i < img->height; i++) {
for (int j = 0; j < img->width; j++) {
for (int k = 0; k < img->nChannels; k++) {
uchar* pixel = &((uchar*)(img->imageData + img->widthStep*i))[j*img->nChannels + k];
int value = pow((float)(*pixel / 255.0), gamma) * 255;
*pixel = (value > 255) ? 255 : ((value < 0) ? 0 : (uchar)value);
}
}
}
```
5. 保存图片
使用OpenCV中的cvSaveImage函数来保存修改后的图片,例如:
```c
cvSaveImage("result.jpg", img);
```
完整代码如下:
```c
#include <cv.h>
#include <highgui.h>
#include <math.h>
int main(int argc, char** argv)
{
IplImage* img = cvLoadImage("image.jpg", CV_LOAD_IMAGE_COLOR);
// 调整亮度
int brightness = 50;
for (int i = 0; i < img->height; i++) {
for (int j = 0; j < img->width; j++) {
for (int k = 0; k < img->nChannels; k++) {
uchar* pixel = &((uchar*)(img->imageData + img->widthStep*i))[j*img->nChannels + k];
int value = *pixel + brightness;
*pixel = (value > 255) ? 255 : (uchar)value;
}
}
}
// 调整对比度
float contrast = 1.5;
for (int i = 0; i < img->height; i++) {
for (int j = 0; j < img->width; j++) {
for (int k = 0; k < img->nChannels; k++) {
uchar* pixel = &((uchar*)(img->imageData + img->widthStep*i))[j*img->nChannels + k];
int value = (int)(*pixel - 128) * contrast + 128;
*pixel = (value > 255) ? 255 : ((value < 0) ? 0 : (uchar)value);
}
}
}
// 调整伽马值
float gamma = 0.5;
for (int i = 0; i < img->height; i++) {
for (int j = 0; j < img->width; j++) {
for (int k = 0; k < img->nChannels; k++) {
uchar* pixel = &((uchar*)(img->imageData + img->widthStep*i))[j*img->nChannels + k];
int value = pow((float)(*pixel / 255.0), gamma) * 255;
*pixel = (value > 255) ? 255 : ((value < 0) ? 0 : (uchar)value);
}
}
}
cvSaveImage("result.jpg", img);
cvReleaseImage(&img);
return 0;
}
```
阅读全文