Search Unity

WebcamTexture getPixels32

Discussion in 'Scripting' started by tonioseiler, Feb 23, 2012.

  1. tonioseiler

    tonioseiler

    Joined:
    Feb 23, 2012
    Posts:
    5
    Hi,

    I need the pixels of webcamtexture in a byte array. But somehow I receive strange data.
    So i tried to populate an array like this:

    Code (csharp):
    1. data = new Color32[webcamTexture.width * webcamTexture.height];
    2. m_vidframe_byte = new Byte[webcamTexture.width * webcamTexture.height * 3];
    3. ...
    4. webcamTexture.GetPixels32(data);
    5.  
    6. for (int i = 0; i < data.Length; i++ )  {
    7.     m_vidframe_byte[3 * i] = data[i].r;
    8.     m_vidframe_byte[3 * i + 1] = data[i].g;
    9.     m_vidframe_byte[3 * i + 2] = data[i].b;
    10. }
    Somehow, the data ist strange, so I try to output the dtaa as Image:


    Code (csharp):
    1. Color[] tmp = new Color[data.Length];
    2.             for (int i = 0; i < tmp.Length; i++) {
    3.                 tmp[i].r = data[i].r;//m_vidframe_byte[3 * i];
    4.                 tmp[i].g = data[i].g;//m_vidframe_byte[3 * i + 1];
    5.                 tmp[i].b = data[i].b;//m_vidframe_byte[3 * i + 2];
    6.             }
    7.            
    8.             // For testing purposes, also write to a file in the project folder
    9.             count++;
    10.            
    11.             var tex = new Texture2D (640, 480, TextureFormat.RGB24, false);
    12.             tex.SetPixels(tmp);
    13.             tex.Apply();
    14.        
    15.             // Encode texture into PNG
    16.             var bytes = tex.EncodeToPNG();
    17.             Destroy (tex);
    18.    
    19.            
    20.             File.WriteAllBytes(Application.dataPath + "/../SavedScreen" + count + ".png", bytes);
    The image looks very strange. Chekcv attachment for it. What is the problem. I am on it since days.

    So please help.
     

    Attached Files:

  2. cyrax

    cyrax

    Joined:
    Dec 20, 2011
    Posts:
    6
    Not sure if you still help on this one... adding just incase someone else comes across this thread.
    m_vidframe_byte = new Byte[webcamTexture.width * webcamTexture.height * 3];
    should be
    m_vidframe_byte = new Byte[webcamTexture.width * webcamTexture.height * 4]; because the format is RBG32 and that's 32 bits not 24 bits.

    Then you will face an interestingly coloured texture. That's because the format is actually BGR and not RGB in m_vidframe_byte:

    for (int i = 0; i < data.Length; i++ ) {
    m_vidframe_byte[3 * i] = data.b; /////////// <- Note this is b and not r
    m_vidframe_byte[3 * i + 1] = data.g;
    m_vidframe_byte[3 * i + 2] = data.r;

    }
     
  3. Dalmia

    Dalmia

    Joined:
    Sep 7, 2012
    Posts:
    7
    Hi
    where do you write this for loop? Is it inside update function or start function?