readPixels - Not detecting certain colours

Hi, I am trying to count the number of pixel of a specific colour. All works well for the most part, however, if my colours values exceed 40 (but is not 255) in either R,G,B or A then the count fails to read the pixel.

For example:
countPixels(tex,40,0,0,255) works
countPixels(tex,0,255,255,255) works

countPixels(tex,41,0,0,255) does not work
countPixels(tex,0,254,254,254) does not work

The pixel format of the texture Im reading from is PIXELFORMAT_R8_G8_B8_A8. Is that correct? (EDIT: I tried a few other formats but it didn’t seem to make any difference)

Something else?

Here is the code:

PixelCountScript.prototype.countPixels = function (texture, r, g, b, a) {

    console.log('Counting pixels R:'+r+" G:"+g+" B:"+b+" A:"+a);

    var oldRenderTarget = this.app.graphicsDevice.renderTarget;
    this.app.graphicsDevice.setRenderTarget(texture);

    var pixels = new Uint8Array(texture.width * texture.height * 4);
  
    //put each pixel into the pixels array
    this.app.graphicsDevice.readPixels(0, 0, texture.width, texture.height, pixels);

    this.app.graphicsDevice.setRenderTarget(oldRenderTarget);

    //read the array and compare each
    var count = 0;
    for (var i = 0; i < pixels.length; i += 4) {
        var pixelR = pixels[i];
        var pixelG = pixels[i + 1];
        var pixelB = pixels[i + 2];
        var pixelA = pixels[i + 3];

        if (pixelR === r && pixelG === g && pixelB === b && pixelA === a) {
            count++;
        }
    }
    
    return count;
};

Something similar takes place here:

It uses custom shader, to make sure there is no gamma correction on colors - you might need to do something similar, instead of using standard material, which gamma corrects colors.

But if you use custom shader pass I suggested in another post, and output the uniform directly, that should not hit that issue.

1 Like

Okay cheers. Unless there is an easy way to prevent gamma correction on a texture, I’m just going to make sure my colour never goes outside those ranges I guess. Thanks