上一篇文章簡單的實現了幾個常見的濾鏡效果,針對每一種濾鏡,在片段着色器中編寫響應的計算邏輯。
但是,隨便一個美顏app、短視頻app的濾鏡都太多了,總不能一個一個寫代碼去吧,況且好些濾鏡特別接近,就讓程序員看一眼,怎麼寫計算邏輯。。
其實,這種風格化的濾鏡是通過把原圖的像素顏色經過過處理,變成另一種顏色來實現的,所以簡單的方法就是使用LUT方法,通過設計師提供的LUT文件來實現預定的濾鏡效果。
具體LUT是什麼,我這裏就不再贅述了,網上很多文章,這裏推薦一個 lut
LUT實現濾鏡的基本思路:
- 準備LUT文件
- 加載LUT文件加載到opengl紋理
- 將紋理傳遞到到片段着色器中
- 根據LUT,在片段着色器中對圖像的顏色值進行映射,得到濾鏡後的顏色進行輸出
LUT文件可以自己製作,也可以從別人項目中拷貝。
LUT文件到opengl紋理
public static int loadTextureFromRes(int resId){
//創建紋理對象
int[] textureId = new int[1];
//生成紋理:紋理數量、保存紋理的數組,數組偏移量
glGenTextures(1, textureId,0);
if(textureId[0] == 0){
Log.e(TAG, "創建紋理對象失敗");
}
//原尺寸加載位圖資源(禁止縮放)
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resId, options);
if (bitmap == null){
//刪除紋理對象
glDeleteTextures(1, textureId, 0);
Log.e(TAG, "加載位圖失敗");
}
//綁定紋理到opengl
glBindTexture(GL_TEXTURE_2D, textureId[0]);
//設置放大、縮小時的紋理過濾方式,必須設定,否則紋理全黑
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//將位圖加載到opengl中,並複製到當前綁定的紋理對象上
texImage2D(GL_TEXTURE_2D, 0, bitmap, 0);
//釋放bitmap資源(上面已經把bitmap的數據複製到紋理上了)
bitmap.recycle();
//解綁當前紋理,防止其他地方以外改變該紋理
glBindTexture(GL_TEXTURE_2D, 0);
//返回紋理對象
return textureId[0];
}
LUT紋理綁定到片段着色器
//amatorka 就是lut文件
int LUTTextureId = GLUtil.loadTextureFromRes(R.drawable.amatorka);
int hTextureLUT = glGetUniformLocation(program, "textureLUT");
glActiveTexture(GL_TEXTURE0 + 1);
glBindTexture(GL_TEXTURE_2D, LUTTextureId);
glUniform1i(hTextureLUT, 1);
片段着色器代碼
#version 300 es
precision mediump float;
in vec2 v_texCoord;
out vec4 outColor;
uniform sampler2D s_texture;
uniform sampler2D textureLUT;
//查找表濾鏡
vec4 lookupTable(vec4 color){
float blueColor = color.b * 63.0;
vec2 quad1;
quad1.y = floor(floor(blueColor) / 8.0);
quad1.x = floor(blueColor) - (quad1.y * 8.0);
vec2 quad2;
quad2.y = floor(ceil(blueColor) / 8.0);
quad2.x = ceil(blueColor) - (quad2.y * 8.0);
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);
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);
vec4 newColor1 = texture(textureLUT, texPos1);
vec4 newColor2 = texture(textureLUT, texPos2);
vec4 newColor = mix(newColor1, newColor2, fract(blueColor));
return vec4(newColor.rgb, color.w);
}
void main(){
vec4 tmpColor = texture(s_texture, v_texCoord);
outColor = lookupTable(tmpColor);
}
效果圖如下
原圖 | lut濾鏡 |
---|---|