opencv學習筆記六:影象灰度線性變換
阿新 • • 發佈:2019-02-14
通過影象灰度線性變換提高影象對比度和亮度,原影象為src,目標影象為dst,則dst(x,y) = * src(x,y) + 。
不僅對單通道影象可以做灰度線性變換,對三通道影象同樣可以。
#include<opencv2/opencv.hpp>; #include<iostream> using namespace cv; using namespace std; int main(int argc, char** argv) { Mat src,dst; src = imread("1.jpg"); if (!src.data) { cout << "could not load image" << endl; return -1; } namedWindow("input", CV_WINDOW_AUTOSIZE); imshow("input", src); int rows = src.rows; int cols = src.cols; float alpha = 1.2, beta = 10; dst = Mat::zeros(src.size(), src.type()); for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { if (src.channels() == 3) { int b = src.at<Vec3b>(row, col)[0]; int g = src.at<Vec3b>(row, col)[1]; int r = src.at<Vec3b>(row, col)[2]; dst.at<Vec3b>(row, col)[0] = saturate_cast<uchar>((alpha*b + beta)); dst.at<Vec3b>(row, col)[1] = saturate_cast<uchar>((alpha*g + beta)); dst.at<Vec3b>(row, col)[2] = saturate_cast<uchar>((alpha*r + beta)); } else if(src.channels()==1){ int v = src.at<uchar>(row, col); dst.at<uchar>(row, col) = saturate_cast<uchar>(alpha*v + beta); } } } namedWindow("output", CV_WINDOW_AUTOSIZE); imshow("output", dst); waitKey(0); return 0; }
執行結果如下: