Unity:读取图像像素颜色并基于该颜色实例化对象

Unity: Reading image pixel color and instantiating object based on that

我需要读取图像像素颜色,图像将只有黑白。因此,如果像素是白色,我想实例化白色立方体,如果像素是黑色,我想实例化黑色立方体。现在这对我来说是全新的,所以我进行了一些挖掘,最后我使用了 system.Drawing 和位图。但是现在我卡住了。我不知道如何检查白色像素

例如

private void Pixelreader()
{
    Bitmap img = new Bitmap(("ImageName.png");
    for (int i = 0; i < img.Width; i++)
    {
        for (int j = 0; j < img.Height; j++)
        {
            System.Drawing.Color pixel = img.GetPixel(i, j);

            if (pixel == *if image is white)
            {
               // instantiate white color.
            }
        }
    }
}

还有其他方法吗?谢谢!

听起来您有点过火了,而是可以使用 Unity 中已经内置的功能。尝试查看在光线投射期间获取像素颜色。

if (Physics.Raycast (ray, hit)) {
     var TextureMap: Texture2D = hit.transform.renderer.material.mainTexture;
     var pixelUV = hit.textureCoord;
         pixelUV.x *= TextureMap.width;
         pixelUV.y *= TextureMap.height;

         print ( "x=" + pixelUV.x + ",y=" + pixelUV.y + " " + TextureMap.GetPixel (pixelUV.x,pixelUV.y) );

Taken from here

您实际上可以将图像作为资源加载到 Texture2D 中,然后使用 UnityEngine.Texture2DUnityEngine.Color.GrayScale 检查您得到的颜色是否足够接近白色。

如果图像是真正的黑白(即所有像素等于 System.Drawing.Color.BlackSystem.Drawing.Color.White),那么您可以直接与这些颜色进行比较。在您发布的代码中,它将如下所示:

if (pixel == System.Drawing.Color.White)
{
    //instantiate white color.
}

如果图像是您的 Unity 资产的一部分,更好的方法是使用资源读取它。将图像放入 Assets/Resources 文件夹;那么你可以使用下面的代码:

Texture2D image = (Texture2D)Resources.Load("ImageName.png");

如果图像全黑或全白,无需循环 - 只需检查一个像素:

if(image.GetPixel(0,0) == Color.White)
{
    //Instantiate white cube
}
else
{
    //Instantiate black cube
}