unity:读取图像像素

unity: read image pixels

我正在尝试读取我的图像有多少像素。它工作正常,但返回错误的像素数。该图像总共有 400 个像素,我只有 256 个。

private void Pixelreader()
{
    // Load image
    Texture2D image = (Texture2D)Resources.Load(texture);
    Debug.Log(image);

    // Iterate through it's pixels
    for (int i = 0; i < image.width; i++)
    {
        for (int j = 0; j < image.height; j++)
        { 
            Color pixel = image.GetPixel(i, j);

            // if it's a white color then just debug...
            if (pixel == Color.white)
            {
                Debug.Log("Im white");
            }
            else 
            {
                Debug.Log("Im black");
            }
        }
    }
}

白色打印 148,黑色打印 108。148 + 108 = 256。所以有很多像素缺失。知道为什么它不读取 400 像素的完整图像吗?

我认为问题在于其余像素不是黑色或白色,只是眼睛看不到的小色调。 尝试调试 image.width * image.height 以获取图像的像素数。

编辑: 您可能应该看看图像检查器中的最大尺寸。可能锁定在256.

~门诺

试试这个:

var whitePixels = 0;
var blackPixels = 0;
for (int i = 0; i < image.width; i++)
    for (int j = 0; j < image.height; j++)
    { 
        Color pixel = image.GetPixel(i, j);

        // if it's a white color then just debug...
        if (pixel == Color.white)
          whitePixels++;
        else 
          blackPixels++;
    }
Debug.Log(string.Format("White pixels {0}, black pixels {1}", whitePixels, blackPixels));

很确定您的输出行只是被截断了。

顺便说一句,"GetPixel" 是出了名的慢,但那是另一回事了。