iOS技术文章iOS技术交流收藏GPUImage Shader源码分析

GPUImageSaturationFilter源码分析

2016-12-13  本文已影响571人  熊皮皮

1、饱和度(Saturation)的定义

饱和度是指某一颜色的“纯度”,或者说,它离纯灰色的距离。当饱和度降低时,该颜色更接近灰色;反之则更纯、更鲜艳。

We think of color saturation as a description of the “purity” of the color, or how far the color is from gray. This is consistent with the notion of saturation in the HLS color system, where saturation is the distance from the pure grays that are at the center of the HLS double cone. If saturation is reduced, the color is more gray; if it is increased, the color is purer and more vivid.
摘自Graphics Shaders: Theory and Practice

2、GPUImageSaturationFilter源码分析

varying highp vec2 textureCoordinate;

uniform sampler2D inputImageTexture;
uniform lowp float saturation;

// Values from "Graphics Shaders: Theory and Practice" by Bailey and Cunningham
const mediump vec3 luminanceWeighting = vec3(0.2125, 0.7154, 0.0721);

void main()
{
    lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);
    lowp float luminance = dot(textureColor.rgb, luminanceWeighting);
    lowp vec3 greyScaleColor = vec3(luminance);
    
    gl_FragColor = vec4(mix(greyScaleColor, textureColor.rgb, saturation), textureColor.w);
}

算法思路:计算每个片元(只有绘制的帧缓冲区大小为原图大小时才有一个片元对应一个像素)的亮度值,以亮度值为基础,根据外部设置的saturation值为系数进行亮度与原始颜色的线性混合。根据mix函数说明

mix(x, y, a) -> x * (1 - a) + y * a

则最终计算为

final_color = luminance(x, y) * (1 - saturation) + rgb(x, y) * saturation。

其中,saturation的变化范围为[0, 2],saturation值越小,颜色越趋近灰色,反之则越鲜艳。0表示完全欠饱和,1为原始颜色值,2表示最大饱和度。

Saturation ranges from 0.0 (fully desaturated) to 2.0 (max saturation), with 1.0 as the normal level

3、效果演示

参考

上一篇下一篇

猜你喜欢

热点阅读