ImagePublisher.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. © CentraleSupelec, 2017
  3. Author: Dr. Jeremy Fix (jeremy.fix@centralesupelec.fr)
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. <http://www.apache.org/licenses/LICENSE-2.0>.
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. // Adjustments to new Publication Timing and Execution Framework
  15. // © Siemens AG, 2018, Dr. Martin Bischoff (martin.bischoff@siemens.com)
  16. using UnityEngine;
  17. namespace RosSharp.RosBridgeClient
  18. {
  19. public class ImagePublisher : UnityPublisher<MessageTypes.Sensor.CompressedImage>
  20. {
  21. public Camera ImageCamera;
  22. public string FrameId = "Camera";
  23. public int resolutionWidth = 640;
  24. public int resolutionHeight = 480;
  25. [Range(0, 100)]
  26. public int qualityLevel = 50;
  27. private MessageTypes.Sensor.CompressedImage message;
  28. private Texture2D texture2D;
  29. private Rect rect;
  30. protected override void Start()
  31. {
  32. base.Start();
  33. InitializeGameObject();
  34. InitializeMessage();
  35. Camera.onPostRender += UpdateImage;
  36. }
  37. private void UpdateImage(Camera _camera)
  38. {
  39. if (texture2D != null && _camera == this.ImageCamera)
  40. UpdateMessage();
  41. }
  42. private void InitializeGameObject()
  43. {
  44. texture2D = new Texture2D(resolutionWidth, resolutionHeight, TextureFormat.RGB24, false);
  45. rect = new Rect(0, 0, resolutionWidth, resolutionHeight);
  46. ImageCamera.targetTexture = new RenderTexture(resolutionWidth, resolutionHeight, 24);
  47. }
  48. private void InitializeMessage()
  49. {
  50. message = new MessageTypes.Sensor.CompressedImage();
  51. message.header.frame_id = FrameId;
  52. message.format = "jpeg";
  53. }
  54. private void UpdateMessage()
  55. {
  56. message.header.Update();
  57. texture2D.ReadPixels(rect, 0, 0);
  58. message.data = texture2D.EncodeToJPG(qualityLevel);
  59. Publish(message);
  60. }
  61. }
  62. }