#Get % of black in a Texture2D

1 messages · Page 1 of 1 (latest)

sullen violet
#

I'm trying to get the % of the color black represents on a Texture2D


    public SpriteRenderer paintSprite;
    Vector3 paintPos;

    public RenderTexture maskProgress;

    private float blackAmountTotal;
    private float blackAmount;


    private Texture2D texture;


    void Start()
    {

        texture= toTexture2D(maskProgress);

        for (int x = 0; x < maskProgress.width; x++)
        {
            for (int y = 0; y < maskProgress.height; y++)
            {
                blackAmountTotal += texture.GetPixel(x, y).a;
            }
        }
        blackAmount= blackAmountTotal;

    }
    Texture2D toTexture2D(RenderTexture rTex)
    {
        Texture2D tex = new Texture2D(rTex.width, rTex.height, TextureFormat.RGB24, false);
        
        RenderTexture.active = rTex;
        tex.ReadPixels(new Rect(0, 0, rTex.width, rTex.height), 0, 0);
        tex.Apply();
        return tex;
    }

void Update(){

  if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out RaycastHit hit))
  {
        Vector2 texCoords = hit.textureCoord;
        paintPos.x = -1 + (texCoords.x * 2);
        paintPos.y = -1 + (texCoords.y * 2);

                int pixelXOffset = (int)paintPos.x - (paintSprite.sprite.texture.width / 2);
                int pixelYOffset = (int)paintPos.y - (paintSprite.sprite.texture.height / 2);
                for (int x = 0; x < paintSprite.sprite.texture.width; x++)
                {
                    for (int y = 0; y < paintSprite.sprite.texture.height; y++)
                    {
                        Color pixelDark = paintSprite.sprite.texture.GetPixel(x, y);
                        Color pixelDarkMask = texture.GetPixel(pixelXOffset + x, pixelYOffset + y);

                        float removedAmount = pixelDirtMask.a - (pixelDarkMask.a * pixelDark.a);
                        blackAmount -= removedAmount;

                    }
                }
    }

}

    private float GetPercentage()
    {
        return blackAmount/ blackAmountTotal;
    }
#

It also lags the game hella

crystal bobcat
#

what are you trying to do

#

because checking each pixel of a texture each frame is obviously expensive

#

i did a simple test and yeah

#

reading 2000000 pixels each frame (for 1920x1080) is an expensive operation

sullen violet
#

Yup

#

I'm trying to get the percentage of blackness in a picture

#

Using it to mask and such