Uploading a photograph to Unity and using it as array

Hey Everyone!

I am trying to create a script that will use a photograph which I created with Matlab by using the im2bw command(it makes a photo black&white). So what I get from Matlab is a 1200x900 array that contains a bunch of 255 and other numbers less than 255 so as I get, it saves this new photo as the uint16 format.

Now, what I am trying to do is use this photograph as an array for my map creator script in unity. But I couldn’t do it. I just wanted to check every single pixel of this black&white photograph(with 2 for loops, you know). If a pixel is black, then the script will create a prefab to its coordinates(like a pixel is at 100x150 coordinates, it will create a prefab at unity world 100x 0y 150z coordinates and so on.)

I need help people… I searched for 6 hours to do this last night but I am desperate.

Okay the process would be this:

  1. Create image (ideally as png format) from matlab image
  2. Assign this image to a Texture2D field.
  3. Use the method Texture2D.GetPixels. Use the image size as parameters so you get the full image’s pixels. This will output a Colour[ ] array.
  4. Cycle through these in a for loop, checking each line. Maybe something similar to:
    public class ExampleThingy : MonoBehaviour
    {
        [Tooltip("Assign the map you want loaded as an image here")]
        public Texture2D texture;
        public Color match;

        public void PixelToWorldMapper()
        {
            Color[] pixels = texture.GetPixels();
            int columns = 0;
            int rows = 0;

            for (int p = 0; p < pixels.Length; p++)
            {
                columns++;
                if(columns >= texture.width)
                {
                    rows++;
                    columns = 0;
                }

                if (pixels[p] == match)
                {
                    // You know it was a match on row 'x' and column 'y'. Use row and column as X and Y coordinates for map system.
                }

            }
        }
    }

I can’t confirm that row and column are the right way round so you’d need to tinker yourself, but it’d just be something like this I think.

1 Like

Why? Can’t you just save in some common lossless format like png? For the rest I don’t see why this wouldn’t work, so how does your code look now?

1 Like

Guys thank you for your support. I was trying to use Nigey’s codes and I found out(after 2 hours omg :smile:) in advanced section, i should tick read/write enable and change “non power of 2” section to “None”. It works! thank you everybody

1 Like