Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying Sepia, RGB, GrayScale effect to UIImage

I want to apply filter effects to image in my app. I am new in Open GL & want to apply Sepia, RGB, GrayScale effect to image in my app. I have implemented Brightness, Contrast, Saturation effects,but was unable to found any solution on Grayscale, RGB & sepia effect.

Thanks in advance.

like image 789
niks Avatar asked Mar 14 '12 10:03

niks


1 Answers

You don't specify whether you want to do this in OpenGL ES 1.1 or 2.0, so I'm going to assume that you are referring to the newer 2.0. If 1.1 is indeed your target, you'll need to play with blend modes like Apple does in their GLImageProcessing example.

For OpenGL ES 2.0, you can use fragment shaders to achieve each of these effects. For a grayscale version of an image, you can extract just the luminance using the following fragment shader:

 precision highp float;

 varying vec2 textureCoordinate;

 uniform sampler2D inputImageTexture;

 const highp vec3 W = vec3(0.2125, 0.7154, 0.0721);

 void main()
 {
     float luminance = dot(texture2D(inputImageTexture, textureCoordinate).rgb, W);

     gl_FragColor = vec4(vec3(luminance), 1.0);
 }

For a sepia tone, you can employ the color matrix manipulation shader I demonstrate in this answer:

 varying highp vec2 textureCoordinate;

 uniform sampler2D inputImageTexture;

 uniform lowp mat4 colorMatrix;
 uniform lowp float intensity;

 void main()
 {
     lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);
     lowp vec4 outputColor = textureColor * colorMatrix;

     gl_FragColor = (intensity * outputColor) + ((1.0 - intensity) * textureColor);
 }

with a matrix of

self.colorMatrix = (GPUMatrix4x4){
        {0.3588, 0.7044, 0.1368, 0},
        {0.2990, 0.5870, 0.1140, 0},
        {0.2392, 0.4696, 0.0912 ,0},
        {0,0,0,0},
    };

I have no idea what you mean by "RGB effect." Perhaps you mean color matrix manipulation, in which case the above will work for you in that case as well.

All of these are built-in filters within my open source GPUImage framework (see the GPUImageBrightnessFilter, GPUImageContrastFilter, GPUImageSaturationFilter, GPUImageSepiaFilter, and GPUImageColorMatrixFilter). If you're truly a newcomer to OpenGL ES, it will take you quite a bit of code to set up your scene, pull in your UIImage as a texture, run a vertex and fragment shader against it, retrieve that image, and save it back out as a UIImage. GPUImage will do all of that for you with a few lines of Objective-C code.

like image 137
Brad Larson Avatar answered Nov 08 '22 16:11

Brad Larson