How to invert texture colours in OpenGL
Asked Answered
V

4

6

I'm texturing a 2D object in OpenGL, and while I have the texture loading fine, I'm just not quite sure how to invert the colours. How do I access the colour information of the bitmap and invert it? Would this be done best in a shader or in the Main program?

I'm leaving this kind of open as I'm not looking for a "fix my code" type of answer, but rather "this is how you access the colour information of the bitmap".

Vulgarize answered 4/2, 2016 at 19:28 Comment(4)
texture format in openGL is simple C array with RGBRGB or RGBARGBA pattern, so, once you load it - change it via revert formula. Other thing - that you may calculate it in shader, but it will be far more costly.Radioscopy
You can either upload an inverted texture in the first place, or make your fragment shader invert it as it reads it.Anesthesiology
I recommend that you start learning the OpenGL Core Profile. In particular, this is trivial to do in a fragment shader.Amitie
What exactly do you mean by "invert"?Adapa
M
8

Its s simple as

gl_FragColor = vec4(1.0 - textureColor.r,1.0 -textureColor.g,1.0 -textureColor.b,1) It is best to do this kind of thing in the shader, if you want to do it once and then reuse it for future draws just use render to texture. This is the fastest way to do color inversion.

EDIT: You use vec4 textureColor = texture2D(uSampler,vTexCoords) before your do gl_FragColor using .r ,.g,.b and .a access the red, green, blue and alpha values respectively.

Manvel answered 4/2, 2016 at 20:4 Comment(1)
Ah that makes sense! I added that into my code, made a few changes here and there, and voila! Thanks!!Vulgarize
N
1
precision mediump float;
uniform sampler2D u_tex;
varying vec2 v_texCoord;
void main()
{
    gl_FragColor = vec4(1,1,1,1) - texture2D(u_tex, v_texCoord);
}
Noriega answered 16/10, 2021 at 0:40 Comment(0)
M
0

I'm writing a vision impaired game and for this I wanted to invert the colors, so white is black etc... which sounds like what you're doing. I eventually hit on this that works and does not involve shaders or modifying the textures. However it does kill blending. So I render to a texture buffer and then do

glLogicOp (GL_COPY_INVERTED);
glEnable (GL_COLOR_LOGIC_OP);

<bind to texture buffer and blit that>

glLogicOp (GL_COPY);
glDisable (GL_COLOR_LOGIC_OP);
Meticulous answered 11/11, 2017 at 13:18 Comment(0)
M
0

Actually, you have to invert the texture coordinates before sampling the texture to achieve that.

So, in fragment shader:

vec2 vert_uv_New=vec2(1-vert_uv.x,1-vert_uv.y);

Now sample it:

gl_FragColor=texture2D(sampler,vert_uv_New);

This will do the job.

Medullated answered 4/7, 2021 at 15:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.