Search Unity

Scanning images and for specific color positions

Discussion in 'Scripting' started by Mohammad-Ishtiaq, Jun 7, 2019.

  1. Mohammad-Ishtiaq

    Mohammad-Ishtiaq

    Joined:
    Sep 18, 2014
    Posts:
    8
    I have been trying to make a program that can scan an image with two colors (Black and White). The program will go through every pixel on the image, and find where all the pixels that are black are located and save the positions in a file. Another option is to create a new object (Like a 3D cube or a pre-made object) where the program detects a black pixel. I have been reading into Texture2D.GetPixel (https://docs.unity3d.com/ScriptReference/Texture2D.GetPixels.html) but it is really confusing. I have also looked online for aid but there isn't much. If anyone knows where I can find some more info like a video or anything that explains this that would be awesome. The image attached is just something I made using an online pixel editor, it is 34 by 34 pixels.
     

    Attached Files:

  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    GetPixels() returns a "flattened" array which you can "convert" to 2D (if I recall correctly) with the formula: index = x + width * y.

    Something like this will generate your cube-world-thingy:
    Code (csharp):
    1.  
    2. Color[] results = texture.GetPixels();
    3.  
    4. for(int y = 0; y < texture.height; ++y)
    5. {
    6.    for(int x = 0; x < texture.width; ++x)
    7.    {
    8.        int index = x + texture.width * y;
    9.  
    10.        if(results[index] == Color.black)
    11.            Instantiate(cubePrefab, new Vector3(x, 0, y), Quaternion.identity);
    12.    }
    13. }
    14.  
    Typed this here so there may be errors.