opencv实现将RGB图像转换到HSI空间

首先是将rbg图像转换为HSI空间内,由于opencv3库中没有直接转换的函数,因此这个转换过程需要自己实现。转换的数学公式如下:

opencv实现的代码如下:

#include
#include
using namespace std;
using namespace cv;

int main()
{
Mat src = imread("D:\\VCprogress\\ConsoleApplication2\\三原色.bmp");
Mat dst = Mat(Size(src.rows, src.cols), CV_8UC3);
vector channels;
split(src, channels);
Mat Hvalue = channels.at(0);
Mat Svalue = channels.at(1);
Mat Ivalue = channels.at(2);


for (int i = 0; i < src.rows; ++i)
for (int j = 0; j {
double H, S, I;
int Bvalue = src.at(i, j)(0);
int Gvalue = src.at(i, j)(1);
int Rvalue = src.at(i, j)(2);


//求Theta =acos((((Rvalue - Gvalue) + (Rvalue - Bvalue)) / 2) / sqrt(pow((Rvalue - Gvalue), 2) + (Rvalue - Bvalue)*                           //(Gvalue - Bvalue)));
double numerator = ((Rvalue - Gvalue) + (Rvalue - Bvalue)) / 2;
double denominator = sqrt(pow((Rvalue - Gvalue), 2) + (Rvalue - Bvalue)*(Gvalue - Bvalue));
if (denominator == 0) H = 0;
else {
double Theta = acos(numerator / denominator) * 180 / 3.14;
if (Bvalue <= Gvalue)
H = Theta;
else  H = 360 - Theta;
}
Hvalue.at(i, j) = (int)(H * 255 / 360); //为了显示将[0~360]映射到[0~255]


  //求S = 1-3*min(Bvalue,Gvalue,Rvalue)/(Rvalue+Gvalue+Bvalue);
int minvalue = Bvalue;
if (minvalue > Gvalue) minvalue = Gvalue;
if (minvalue > Rvalue) minvalue = Rvalue;
numerator = 3 * minvalue;
denominator = Rvalue + Gvalue + Bvalue;
if (denominator == 0)  S = 0;
else {
S = 1 - numerator / denominator;
}
Svalue.at(i, j) = (int)(S * 255);//为了显示将[0~1]映射到[0~255]


I = (Rvalue + Gvalue + Bvalue) / 3;
Ivalue.at(i, j) = (int)(I);
}


merge(channels, dst);
namedWindow("HSI");
imshow("HSI", dst);
imwrite("HSI空间图像.jpg", dst);


原始图像如下:opencv实现将RGB图像转换到HSI空间_第1张图片     HSI空间转换后的图像如下:opencv实现将RGB图像转换到HSI空间_第2张图片

你可能感兴趣的:(opencv实现将RGB图像转换到HSI空间)