【问题标题】:C# Unity - Extract pixel array from camera in unity and display in pythonC# Unity - 统一从相机中提取像素数组并在 python 中显示
【发布时间】:2020-07-10 14:01:23
【问题描述】:

我正在尝试做两件事:

  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()

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

【问题讨论】:

  • 你试过 Image.frombytes() 吗?如果你能以某种方式发送一个指向 .txt 文件的链接,我可以检查我是否可以让它工作。

标签: python c# arrays unity3d ml-agent


【解决方案1】:

我不确定(不详细了解 python),但我认为 GetRawTextureData 不是您想要在这里使用的。

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

将此纹理编码为 JPG 格式。

返回的字节数组是 JPG“文件”。您可以将它们写入磁盘以获取 JPG 文件、通过网络发送等。

此功能仅适用于未压缩的非 HDR 纹理格式。您必须在 Texture Import Settings 中启用纹理的 Read/Write Enabled 标志。编码后的 JPG 数据将没有 Alpha 通道。

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    • 1970-01-01
    相关资源
    最近更新 更多