'Compressing Texture2D with SetPixel() return weird colors in Unity

As the title said, I'm compressing an image (inputed as a Texture2D) by dividing the image into blocks and taking the average r, g, and b value.

Image:

enter image description here

But the result is mostly gray-ish color with a diagonal strip of other colors in the middle:

enter image description here

This is the code for compression:

private void ASCIIConvert()
{
    texWidth = tex.width; texHeight = tex.height;

    int blockHeight = Mathf.FloorToInt((float)texHeight / neededHeight);
    int blockWidth = Mathf.FloorToInt((float)texWidth / neededWidth);
    int maxHeight = blockHeight * neededHeight;
    int maxWidth = blockWidth * neededWidth;
    int numBlockHeight = maxHeight/blockHeight;
    int numBlockWidth = maxWidth/blockWidth;

    tex2 = new Texture2D(numBlockWidth, numBlockHeight);
    for (int idx = 0; idx < maxHeight; idx += blockHeight)
    {
        int curBlockHeight = Mathf.FloorToInt((float) idx / blockHeight);

        for (int j = 0; j < maxWidth; j += blockWidth)
        {
            float sumr = 0, sumg = 0, sumb = 0;
            int curBlockWidth = Mathf.FloorToInt((float) idx / blockWidth);

            for (int m = idx * blockHeight; m < idx * blockHeight + blockHeight; m++)
            {
                for (int n = j * blockWidth; n < j * blockWidth + blockWidth; n++)
                {
                    sumr += tex.GetPixel(n,m).r;
                    sumg += tex.GetPixel(n,m).g;
                    sumb += tex.GetPixel(n,m).b;
                }
            }

            sumr /= (blockWidth * blockHeight);
            sumg /= (blockWidth * blockHeight);
            sumb /= (blockWidth * blockHeight);

            tex2.SetPixel(curBlockWidth, curBlockHeight, new Color(sumr, sumg, sumb, 1f));
        }
    }
    tex2.Apply();

    //standard
    newSprite = Sprite.Create(tex2, new Rect(0.0f, 0.0f, tex2.width, tex2.height), new Vector2(0.5f, 0.5f), 100.0f);
    imgContainer.GetComponent<SpriteRenderer>().sprite = newSprite;
}

neededWidth and neededHeight are length and width of the wanted compressed texture. Any idea where the compression may have gone wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source