在进行一个AR项目,需要进行抠图,所以就用了一些抠图的方法,先展示一下抠图效果,如下:
蓝色背景
RGB值 : 0, 71, 187
CMYK : 90, 68, 0, 0
绿色背景
RGB值: 0, 177, 64
CMYK : 81, 0, 92, 0
RGB值转换成(0-1)之间,需要除以255
我们直接在fragment shader中进行抠图。
抠图算法方案一:
keying_color = vec3(0.0, 0.6941177, 0.2509804) 是需要扣掉的rgb值,计算2个像素的色差值,色差值在一定阈值智能进行抠图:
#extension GL_OES_EGL_image_external: require
precision mediump float;
varying vec2 varTexCoordAlpha;
uniform samplerExternalOES texture;
void main() {
vec4 texColor = texture2D(texture, vec2(varTexCoordAlpha.x,1.0-varTexCoordAlpha.y));
vec3 keying_color = vec3(0.0, 0.6941177, 0.2509804);
float thresh = 0.6; // [0, 1.732]
float slope = 0.50; // [0, 1]
vec3 input_color = texColor.rgb;
float d = abs(length(abs(keying_color.rgb - input_color.rgb)));
float edge0 = thresh * (1.0 - slope);
float alpha = smoothstep(edge0, thresh, d);
gl_FragColor = vec4(input_color, alpha);
}
抠图算法方案二:
这个算法是查询到的,具体的可以看一下参考文档进行研究一下。
#extension GL_OES_EGL_image_external: require
precision mediump float;
varying vec2 varTexCoordAlpha;
uniform samplerExternalOES texture;
void main() {
vec4 texColor = texture2D(texture, vec2(varTexCoordAlpha.x,1.0-varTexCoordAlpha.y));
float rbAverage = texColor.r * 0.5 + texColor.b * 0.5;
float gDelta = texColor.g - rbAverage;
texColor.a = 1.0 - smoothstep(0.0, 0.15, gDelta);
texColor.a = texColor.a * texColor.a * texColor.a;
gl_FragColor = texColor;
}
参考文档:
https://www.opengl.org/sdk/docs/tutorials/ClockworkCoders/discard.php
https://stackoverflow.com/questions/17444734/opengl-es-green-screen-but-i-want-to-use-black