目录
- 概念
- C++源码
- 变换函数
- 主函数
- 效果
- 完整源码
平台:Windows 10 20H2
Visual Studio 2015
OpenCV 4.5.3
本文内容节选自《数字图像处理》第三版
C++源码修改自C++数字图像处理(1)-伽马变换 —— 图像大师
概念
C++源码
变换函数
//函数名:gammaTransformation
//作用:实现伽马变换
//参数:
//matInput:输入图像
//fGamma : 伽马值
//fC : C值(缩放系数)
//返回值 :变换后的图像
Mat gammaTransformation(cv::Mat matInput, float fGamma, float fC = 1.0f)
{Mat chRGB[3];Mat matOutput[3];Mat output = matInput.clone();split(matInput, chRGB);for (unsigned char k = 0; k < 3; ++k){//构造输出图像matOutput[k] = cv::Mat::zeros(chRGB[k].rows, chRGB[k].cols, chRGB[k].type());//循环中尽量避免除法float fNormalFactor = 1.0f / 255.0f;for (size_t r = 0; r < chRGB[k].rows; r++){unsigned char* pInput = chRGB[k].data + r * chRGB[k].step[0];unsigned char* pOutput = matOutput[k].data + r * matOutput[k].step[0];for (size_t c = 0; c < chRGB[k].cols; c++){//gamma变换float fOutput = std::pow(pInput[c] * fNormalFactor, fGamma) * fC;//数值溢出判断fOutput = fOutput > 1.0f ? 1.0f : fOutput;//输出pOutput[c] = static_cast<unsigned char>(fOutput * 255.0f);}}}merge(matOutput, 3, output);return output;
}
主函数
图片路径根据实际情况调整,注意反斜杠是转义字符的开头,故“\”应替换为“\\”
int main(int argc, char * argv[])
{string GammaPic = "Gamma=";float Gamma = 0.5;Mat Image = imread("D:\\Work\\OpenCV\\Workplace\\Test_1\\1.jpg");imshow("原图", Image);imshow(GammaPic + to_string(Gamma) + "变换后", gammaTransformation(Image, Gamma));waitKey(0);return 0;
}
效果
Gamma = 0.5 时
Gamma = 2 时
完整源码
#include <opencv2/opencv.hpp>
#include <iostream>using namespace cv;
using namespace std;//函数名:gammaTransformation
//作用:实现伽马变换
//参数:
//matInput:输入图像
//fGamma : 伽马值
//fC : C值(缩放系数)
//返回值 :变换后的图像
Mat gammaTransformation(cv::Mat matInput, float fGamma, float fC = 1.0f)
{Mat chRGB[3];Mat matOutput[3];Mat output = matInput.clone();split(matInput, chRGB);for (unsigned char k = 0; k < 3; ++k){//构造输出图像matOutput[k] = cv::Mat::zeros(chRGB[k].rows, chRGB[k].cols, chRGB[k].type());//循环中尽量避免除法float fNormalFactor = 1.0f / 255.0f;for (size_t r = 0; r < chRGB[k].rows; r++){unsigned char* pInput = chRGB[k].data + r * chRGB[k].step[0];unsigned char* pOutput = matOutput[k].data + r * matOutput[k].step[0];for (size_t c = 0; c < chRGB[k].cols; c++){//gamma变换float fOutput = std::pow(pInput[c] * fNormalFactor, fGamma) * fC;//数值溢出判断fOutput = fOutput > 1.0f ? 1.0f : fOutput;//输出pOutput[c] = static_cast<unsigned char>(fOutput * 255.0f);}}}merge(matOutput, 3, output);return output;
}int main(int argc, char * argv[])
{string GammaPic = "Gamma=";float Gamma = 2;Mat Image = imread("D:\\Work\\OpenCV\\Workplace\\Test_1\\1.jpg");imshow("原图", Image);imshow(GammaPic + to_string(Gamma) + "变换后", gammaTransformation(Image, Gamma));waitKey(0);return 0;
}