用于计算像素数的着色器

Shader for counting number of pixels

我正在寻找着色器 CG 或 HLSL,它们可以计算红色像素或我想要的任何其他颜色的数量。

您可以在片段着色器中使用 atomic counters 执行此操作。只需测试输出颜色,看看它是否在一定的红色容差范围内,如果是,则增加计数器。在绘制调用之后,您应该能够在 CPU 上读取计数器的值并用它做任何您喜欢的事情。

编辑:添加了一个非常简单的示例片段着色器:

// Atomic counters require 4.2 or higher according to
// https://www.opengl.org/wiki/Atomic_Counter

#version 440
#extension GL_EXT_gpu_shader4 : enable

// Since this is a full-screen quad rendering, 
// the only input we care about is texture coordinate. 
in vec2 texCoord;

// Screen resolution
uniform vec2 screenRes;

// Texture info in case we use it for some reason
uniform sampler2D tex;

// Atomic counters! INCREDIBLE POWER
layout(binding = 0, offset = 0) uniform atomic_uint ac1;

// Output variable!
out vec4 colorOut;

bool isRed(vec4 c)
{
    return c.r > c.g && c.r > c.b;
}

void main() 
{
    vec4 result = texture2D(tex, texCoord);

    if (isRed(result))
    {
        uint cval = atomicCounterIncrement(ac1);
    }

    colorOut = result;
}

您还需要在代码中设置原子计数器:

GLuint acBuffer = 0;
glGenBuffers(1, &acBuffer);

glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, acBuffer);
glBufferData(GL_ATOMIC_COUNTER_BUFFER, sizeof(GLuint), NULL, GL_DYNAMIC_DRAW);