Lut的全称是显示查找表(Look-Up-Table),对应着一种映射关系。在图像调色中用到很多。
使用Lut可以轻松得到变换之后的颜色:
Trans_color = LutTrans(color);
但是一个完整的色域信息是 256*256*256
就算是一个信息只有1字节,这个信息也有16MB的大小,对于工程来讲实在是太大了。
所以在实际的工程中,通常使用n*n*n
的信息空间来概略的表示256*256*256
的信息空间。
比如使用
64*64*64
,将其分解为64*64*8*8
即512*512
的图像大小。
图像的横纵坐标(x,y)
可以表示为(x1*64+x2,y1*64+y2)
,那么通过(x1,y1)
可以得到第一个色道**(Blue),通过x2
可以得到第二个色道(Red),通过y2
可以得到第三个色道(Green)**。
标准的Lut图像就是将0~255的分量等分为n份。
当n为64的时候,设其映射关系为:
区间 映射值
0 ~ 4 -> 0
4 ~ 8 -> 4
8 ~ 12 -> 8
...
252 ~ 256 -> 252
这样是均匀的映射关系
除了正方形的Lut图像,还有线性的Lut图像,其生成代码分别为:
void generate_Lut_Square(int len)
{
Mat gen_lut_img(len * sqrt(len), len * sqrt(len), CV_8UC3, Scalar(255, 0, 0));
for (int i = 0; i < gen_lut_img.rows; i++)
{
for (int j = 0; j < gen_lut_img.cols; j++)
{
int blue_rows = i / len;
int blue_clos = j / len;
int blue_value = blue_rows * sqrt(len) + blue_clos;
int green_value = i % len;
int red_value = j % len;
gen_lut_img.at(i, j) = Vec3b(blue_value * 256 / len, green_value * 256 / len, red_value * 256 / len);
}
}
imshow("LutAns", gen_lut_img);
imwrite("../lut_ans16.png", gen_lut_img);
}
void generate_Lut_Line(int len)
{
Mat gen_lut_img(len, len * len, CV_8UC3, Scalar(255, 0, 0));
for (int i = 0; i < gen_lut_img.rows; i++)
{
for (int j = 0; j < gen_lut_img.cols; j++)
{
int blue_value = j / len;
int green_value = i % len;
int red_value = j % len;
gen_lut_img.at(i, j) = Vec3b(blue_value * 256 / len, green_value * 256 / len, red_value * 256 / len);
}
}
imshow("LutAns", gen_lut_img);
imwrite("../lut_ans_line.png", gen_lut_img);
}
若想在CPU中计算使用lut,lut的值是一一对应的,不会出现浮点插值的问题。
Vec3b LutTrans(Vec3b color)
{
int blue_rows = color[0] / 4 / 8; //0~255 -> 0~63 -> 0~7
int blue_cols = color[0] / 4 % 8; //0~255 -> 0~63 -> 0~7
int green_rows = color[1] / 4; //0~255 -> 0~63
int red_cols = color[2] / 4; //0~255 -> 0~63
int ans_rows = blue_rows * 64 + green_rows;
int ans_cols = blue_cols * 64 + red_cols;
return lut_img.at(ans_rows, ans_cols);
}
但是当lut技术用在gpu中的时候,因为取值使用的函数是texture2D
,所以取值会出现浮点误差,这时候就需要根据浮点数的到所谓整点的距离来计算其对应的颜色值。
vec4 LutTransDlx(vec4 color){
highp float blueColor = color.b * 63.0;
// 根据B通道获取小正方形格子(64x64格子)
//向下取值
highp vec2 quad1;
quad1.y = floor(floor(blueColor) / 8.0);
quad1.x = floor(blueColor) - (quad1.y * 8.0);
//向上取值
highp vec2 quad2;
quad2.y = floor(ceil(blueColor) / 8.0);
quad2.x = ceil(blueColor) - (quad2.y * 8.0);
// 根据小正方形格子和RG通道,获取纹理坐标,每个大格子的大小:1/8=0.125,每个小格子的大小:1/512
highp vec2 texPos1;
texPos1.x = (quad1.x * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * color.r);
texPos1.y = (quad1.y * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * color.g);
highp vec2 texPos2;
texPos2.x = (quad2.x * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * color.r);
texPos2.y = (quad2.y * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * color.g);
lowp vec4 newColor1 = texture2D(lutTexture, texPos1);
lowp vec4 newColor2 = texture2D(lutTexture, texPos2);
//返回其小数部分
lowp vec4 newColor = mix(newColor1, newColor2, fract(blueColor));
return newColor;
}