DIY Blend Modes

Hey guys,

Since OpenFrameworks doesn’t provide a difference blend mode of its own, I’m trying to figure out the best way to write my own. My first thought was to load the two images into ofPixel objects, then loop through and perform the necessary operations on a per-pixel basis. This would probably work, but seems horribly inefficient from a performance perspective.

Does anyone have suggestions on a better way of approaching this?

Maybe you can use a shader to do this. Pass the textures of your two images to a fragment shader and do the blending in it.
Something like this:

fragment shader:

#version 150

uniform sampler2DRect tex1;
uniform sampler2DRect tex2;

in vec2 texCoordVarying;

out vec4 color;

void main(){

    vec4 c1 = texture(tex1, texCoordVarying);
    vec4 c2 = texture(tex2, texCoordVarying);
    // Do the blending here:
    color = (c1+c2)/2.0;

vertex shader:

#version 150

uniform mat4 modelViewProjectionMatrix;

in vec4 position;
in vec2 texcoord;

out vec2 texCoordVarying;

void main(){
    gl_Position = modelViewProjectionMatrix * position;
    texCoordVarying = texcoord;

And in your ofApp::draw():

void ofApp::draw(){
        shader.setUniformTexture("tex1", img1.getTextureReference(), 0);
        shader.setUniformTexture("tex2", img2.getTextureReference(), 1);
        img1.draw(0, 0);

OF does include different blend modes.
Use ofEnableBlendMode(ofBlendMode);
and ofDisableBlendMode()

enum ofBlendMode{

@Elaye – Thank you! Took me a little while to learn my way around GLSL, but I’ve got it up and running now.

@roymacdonald-- The blend mode I was looking for was “Difference,” which is sort of like “Subtract” except that it returns the absolute value of negative numbers, rather than just clamping to zero. I did find it a little strange how sparse the list of default blend modes was, but then my background is in animation and vfx so I might be a little skewed in my expectations :wink:

This has been, if nothing else, a great reason to finally make the push into GLSL. Thanks guys!

Hi there!

I think this shadertoy link might be helpful. If you want to know a bit more of how this works, I recommend the following websites:

W3: Compositing and Blending
and Easy RGB: Color Math

Good work!

1 Like

Hey @SFBurning this is what you need then


BTW: go to there are all the openFrameworks addons available, sorted and listed. super nice

1 Like