Skip to content
{{ message }}

Instantly share code, notes, and snippets.

# Volcanoscar/greyscale.frag

Forked from wiseoldduck/greyscale.frag
Created Jan 19, 2017
A simple glsl color -> greyscale shader, using luminosity method
 // fragment shader // // RGBA color to RGBA greyscale // // smooth transition based on u_colorFactor: 0.0 = original, 1.0 = greyscale // // http://www.johndcook.com/blog/2009/08/24/algorithms-convert-color-grayscale/ // "The luminosity method is a more sophisticated version of the average method. // It also averages the values, but it forms a weighted average to account for human perception. // We’re more sensitive to green than other colors, so green is weighted most heavily. The formula // for luminosity is 0.21 R + 0.72 G + 0.07 B." varying vec2 v_texCoord; uniform sampler2D CC_Texture0; uniform float u_colorFactor; void main() { vec4 sample = texture2D(CC_Texture0, v_texCoord); float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b; gl_FragColor = vec4(sample.r * u_colorFactor + grey * (1.0 - u_colorFactor), sample.g * u_colorFactor + grey * (1.0 - u_colorFactor), sample.b * u_colorFactor + grey * (1.0 - u_colorFactor), 1.0); }

### skident commented Jul 4, 2019

 These two lines are contradict to each other, so you should change one of them: `0.0 = original, 1.0 = greyscale` `sample.r * u_colorFactor + grey * (1.0 - u_colorFactor)` I suggest You use next variant: ``````// 0.0 = original, 1.0 = greyscale gl_FragColor = vec4(sample.rgb * (1.0 - u_colorFactor) + (grey * u_colorFactor), 1.0); ``````

### ccritchfield commented Mar 2, 2021 • edited

 condensed down using intrinsic glsl funcs...(can't get teh code to newline properly in the comment...) void main() `{ vec4 sample = texture2D(CC_Texture0, v_texCoord); vec3 lum = vec3(0.21, 0.71, 0.07); float grey = dot(sample.rgb, lum.rgb); gl_FragColor.rgb = mix( grey.rgb, sample.rgb, vec3(u_colorFactor) ); gl_FragColor.a = 1.0; }`
to join this conversation on GitHub. Already have an account? Sign in to comment