How to read pixels from texture2d to a list ?

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class ReadPixelsFromImage : MonoBehaviour
{
    public Texture2D tx2d;

    // Start is called before the first frame update
    void Start()
    {
        ReadPixelsFromT2D(tx2d);
    }

    // Update is called once per frame
    void Update()
    {

    }

    private void ReadPixelsFromT2D(Texture2D Texture)
    {
        Texture2D tex = new Texture2D(Texture.width, Texture.height, TextureFormat.RGB24, false);


        // Initialize and render
        RenderTexture rt = new RenderTexture(Texture.width, Texture.height, 24);
        Camera.main.targetTexture = rt;
        Camera.main.Render();
        RenderTexture.active = rt;

        // Read pixels
        tex.ReadPixels(new Rect(0, 0, tx2d.width, tx2d.height), 0, 0);

        Camera.main.targetTexture = null;
        RenderTexture.active = null; // added to avoid errors
        DestroyImmediate(rt);
    }
}

i want to see all the pixels in a list but ReadPixels is a void.

ReadPixels reads the pixels from a render texture into a Texture2D. This is essentially a GPU to RAM transfer. In order to access the data in ram you just have to use GetPixels or GetPixels32 on the texture after you filled it with the data from the render texture.

Your method doesn’t make much sense. You pass in a Texture2d, but all you do with that texture is using it’s width and height to create a new Texture2D you called tex and a render texture with the same width and height. Even more crazy you then reach out of your method to the class variable tex2d and grab it’s width and height to use it in the ReadPixels call. Though you call ReadPixels on your new “tex” texture. That tex texture isn’t used or passed anywhere else. So your method needs some heavy refactoring.

1 Like