更改图像的亮度和对比度
Posted
技术标签:
【中文标题】更改图像的亮度和对比度【英文标题】:Changing brightness and contrast of an image 【发布时间】:2013-05-20 09:26:41 【问题描述】:我正在编写以下代码
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace std;
using namespace cv;
Mat change(Mat m);
int main()
Mat image = imread("C:/Users/Public/Pictures/Sample Pictures/Penguins.jpg");
Mat copy = Mat::zeros(image.size(),image.type());
Mat changedImage = change(copy);
namedWindow("Image");
imshow("Image",changedImage);
waitKey(0);
Mat change(Mat m)
int cols = m.cols;
int rows = m.rows;
double alpha = 2.2;
int beta = 50;
for(int i=0;i<rows;i++)
for(int c=0;c<cols;c++)
m.at<Vec3b>(rows,c)[0] = saturate_cast<uchar>(alpha* (m.at<Vec3b>(rows,cols)[0]) + beta);
m.at<Vec3b>(rows,c)[1] = saturate_cast<uchar>(alpha* (m.at<Vec3b>(rows,cols)[1]) + beta);
m.at<Vec3b>(rows,c)[2] = saturate_cast<uchar>(alpha* (m.at<Vec3b>(rows,cols)[2]) + beta);
return m;
这编译得很好,但是当我运行它时,我得到了以下错误
OpenCV Error: Assertion failed (dims <= 2 && data && (unsigned)i0 < (unsigned)si
ze.p[0] && (unsigned)(i1*DataType<_Tp>::channels) < (unsigned)(size.p[1]*channel
s()) && ((((sizeof(size_t)<<28)|0x8442211) >> ((DataType<_Tp>::depth) & ((1 << 3
) - 1))*4) & 15) == elemSize1()) in unknown function, file c:\opencv\build\inclu
de\opencv2\core\mat.hpp, line 534
为什么我会得到这个?我想我所做的一切都是正确的。
【问题讨论】:
嗨,为什么不在这个问题中使用矩阵算术运算符:[***.com/questions/16473695/… changedimage=(2.2*image)+cvScalar(50,50,50); 【参考方案1】:试试这个代码。
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace std;
using namespace cv;
Mat change(Mat m);
int main()
Mat image = imread("C:/Users/Public/Pictures/Sample Pictures/Penguins.jpg");
Mat changedImage = change(image); //Modified
namedWindow("Image");
imshow("Image",changedImage);
waitKey(0);
Mat change(Mat m)
int cols = m.cols;
int rows = m.rows;
double alpha = 2.2;
int beta = 50;
for(int i=0;i<rows;i++)
for(int c=0;c<cols;c++)
m.at<Vec3b>(i,c)[0] = saturate_cast<uchar>(alpha* (m.at<Vec3b>(i,c))[0]) + beta); //Modified
m.at<Vec3b>(i,c)[1] = saturate_cast<uchar>(alpha* (m.at<Vec3b>(i,c))[1]) + beta); //Modified
m.at<Vec3b>(i,c)[2] = saturate_cast<uchar>(alpha* (m.at<Vec3b>(i,c))[2]) + beta); //Modified
return m;
【讨论】:
【参考方案2】:试试这个...
Mat Change(Mat input,int beta = 50)
Mat Output;
Scalar S(beta,beta,beta);
cv::add(input,S,Output);
return Output;
【讨论】:
以上是关于更改图像的亮度和对比度的主要内容,如果未能解决你的问题,请参考以下文章