我使用 PyTorch 训练了一个模型。在 Unity 中,我使用 aWebCamTexture
来显示实时视频。如何将网络摄像头帧输入 PyTorch 模型,然后使用模型的输出在 Unity 中执行操作?
我找到了 Unity ML-agents,但它似乎对这种情况没有帮助。
我使用 PyTorch 训练了一个模型。在 Unity 中,我使用 aWebCamTexture
来显示实时视频。如何将网络摄像头帧输入 PyTorch 模型,然后使用模型的输出在 Unity 中执行操作?
我找到了 Unity ML-agents,但它似乎对这种情况没有帮助。
您可以在每次更新时捕获 cam 数据,然后通过将刚刚捕获的数据提供给它来运行您的 pytorch 模型。我没有尝试过,也不确定 pytorch 是如何工作的,但是对于通用 python 脚本,你可以执行以下操作:
...
void Start()
{
...
data = new Color32[webcamTexture.width * webcamTexture.height];
...
}
...
void FixedUpdate ()
{
...
webCamTexture.GetPixels32(data); //this is faster than returning a Color32 object
...
}
...
private void runPython(string pathToPythonExecutable, string pyTorchScript, Color32[] data)
{
var startInfo = new ProcessStartInfo();
var pyTorchArgs = convertDataToYourPyTorchInputFormat (data)
startInfo.Arguments = string.Format("{0} {1}", pyTorchScript, pyTorchArgs);
startInfo.FileName = pathToPythonExecutable;
startInfo.UseShellExecute = false;
var process = Process.Start(start));
process.WaitForExit();
//do stuff in unity with the return value of process (process.ExitCode) or whatever.
}
请注意,这可能会产生大量开销来使用外部可执行文件创建和结束进程。有一些库允许您在 c# 中运行 python 脚本。我可以想到 2:IronPython ( http://ironpython.net ) 和 Python for .Net ( http://pythonnet.github.io ) 不过我从未尝试过它们。