Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Publish game camera stream via ROS

Discussion in 'Robotics' started by marcociaraleo, Jun 11, 2021.

  1. marcociaraleo

    marcociaraleo

    Joined:
    May 13, 2021
    Posts:
    2
    Hello everyone,
    I was wondering, how to stream the camera during game via ROS to a ROS subscriber via the robotics package?
    Do you know where is it possible to find a script able to achieve that?

    Thanks!

    Marco
     
  2. LaurieUnity

    LaurieUnity

    Unity Technologies

    Joined:
    Oct 23, 2020
    Posts:
    77
    Hi marco, that would probably look something like this -

    Code (CSharp):
    1. void SendImage(Camera sensorCamera, string topicName)
    2. {
    3.   var oldRT = RenderTexture.active;
    4.   RenderTexture.active = sensorCamera.targetTexture;
    5.   sensorCamera.Render();
    6.  
    7.   // Copy the pixels from the GPU into a texture so we can work with them
    8.   // For more efficiency you should reuse this texture, instead of creating a new one every time
    9.   Texture2D camText = new Texture2D(sensorCamera.targetTexture.width, sensorCamera.targetTexture.height);
    10.   camText.ReadPixels(new Rect(0, 0, sensorCamera.targetTexture.width, sensorCamera.targetTexture.height), 0, 0);
    11.   camText.Apply();
    12.   RenderTexture.active = oldRT;
    13.  
    14.   // Encode the texture as a PNG, and send to ROS
    15.   byte[] imageBytes = camText.EncodeToPNG();
    16.   var message = new MCompressedImage(new MHeader(), "png", imageBytes);
    17.   RosConnection.instance.Send(topicName, message);
    18. }
     
  3. marcociaraleo

    marcociaraleo

    Joined:
    May 13, 2021
    Posts:
    2
    Hi Laurie,
    thank you a lot for the snippet. Do you know if this work with any rendering pipeline? I am constrained to URP/HDRP due to perception package compatibility.
     
  4. LaurieUnity

    LaurieUnity

    Unity Technologies

    Joined:
    Oct 23, 2020
    Posts:
    77