用于计算像素数的着色器

时间:2015-03-30 17:57:13

标签: graphics unity3d glsl hlsl

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

1 个答案:

答案 0 :(得分:1)

您可以在片段着色器中使用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);