C# Unity - 统一从相机中提取像素数组并以 python 显示

C# Unity - Extract pixel array from camera in unity and display in python

我正在尝试做两件事:

  1. 从相机中检索 84 x 84 x 3 像素阵列
  2. 将此数组发送到 python 可以显示它的脚本

我坚持使用 1),所以目前我只是将字节数组写入一个 txt 文件,然后在 python 中打开该文件。但是,我不断收到这张图片,这让我相信字节数组实际上并没有用像素数据正确实例化。 [] 1

这是 C# 统一代码:

using System.IO;
using UnityEngine;
using MLAgents.Sensors;
// using UnityEngine.CoreModule;

public class TrainingAgent : Agent, IPrefab
{

    public Camera cam;
    private RenderTexture renderTexture;
    public int bytesPerPixel;
    private byte[] rawByteData;
    private Texture2D texture2D;
    private Rect rect;


    public override void Initialize()
    {

        renderTexture = new RenderTexture(84, 84, 24);
        rawByteData = new byte[84 * 84 * bytesPerPixel];
        texture2D = new Texture2D(84, 84, TextureFormat.RGB24, false);
        rect = new Rect(0, 0, 84, 84);
        cam.targetTexture = renderTexture;
    }

    public override void CollectObservations(VectorSensor sensor)
    {
        run_cmd();
    }

    private void run_cmd()
    {

        cam.Render();
        // Read pixels to texture
        RenderTexture.active = renderTexture;
        texture2D.ReadPixels(rect, 0, 0);
        Array.Copy(texture2D.GetRawTextureData(), rawByteData, rawByteData.Length);
        File.WriteAllBytes("/Path/to/byte/array/Foo.txt", rawByteData); // Requires System.IO
    }
}

这里是 python 代码:

from PIL import Image
import numpy as np
fh = open('/Path/to/byte/array/foo.txt', 'rb')
ba = bytearray(fh.read())
data = np.array(list(ba)).reshape(84,84,3)
img = Image.fromarray(data, 'RGB')
img.show()

任何帮助将不胜感激,因为我不知道我哪里出错了,而且我的调试尝试似乎是徒劳的。

我不确定(不知道 python 的细节)但我认为 GetRawTextureData 不是你想在这里使用的。

您宁愿导出实际的图像二进制文件,例如使用 ImageConversion.EncodeToJPG (former Texture2D.EncodeToJPG)

的 JPG

Encodes this texture into JPG format.

The returned byte array is the JPG "file". You can write them to disk to get the JPG file, send them over the network, etc.

This function works only on uncompressed, non-HDR texture formats. You must enable the texture's Read/Write Enabled flag in the Texture Import Settings. The encoded JPG data will have no alpha channel.

然后将其作为实际图像文件加载到 python 中。

在您的代码中,这相当于将最后两行 C# 替换为:

rawByteData = ImageConversion.EncodeToJPG(texture2D);
File.WriteAllBytes("/Path/to/jpg/foo.jpg", rawByteData);