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



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

例如

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.
            }
        }
    }
}

还有其他方法可以做到这一点吗?谢谢!

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

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

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

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

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

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

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

听起来你有点过火了,而是可以使用 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) );

取自这里

最新更新