UFLD车道线检测集成unity方法二

一.参考在Unity中集成Python开发与运行_我喜欢就喜欢的博客-CSDN博客_python与unity

二.详细步骤

1.找到项目在资源显示器中显示

 2.进入 New Unity Project—>Packages—>manifset,json

3.在其中插入 "com.unity.scripting.python": "5.0.0-pre.5",

4.进入unity项目,编辑中项目设置会出现

5.通过窗口—>常规—>python console 调用python窗口并践行验证

6.将python项目导入到Assets当中

三.编写python脚本将cmd命令集成到其中

1.第一次的test.py脚本无法运行,原因是每次打开一个新的黑窗口

import os
os.system("activate lane-det")
os.system("f:")
os.system("cd Ultra-Fast-Lane-Detection-master")
os.system("python demo.py configs//tusimple.py --test_model tusimple_18.pth ")

后尝试使用&&和;将多句cmd命令组合成一个,也失败,可能是python本身的bug,其他人电脑可运行,尝试多重方法,只能用+来运行两个命令

import os
os.system('start cmd /k'+' activate lane-det')

错误的代码从新命名为run-cmd-2.py

2.新的方法参考python:subprocess模块连续执行多条cmd命令_存雪的博客-CSDN博客_subprocess执行多条命令

import os,subprocess
# -*- encoding=utf-8 -*-
from subprocess import Popen, PIPE, STDOUT
#进入/sdcard 下,查看文件列表
#使用gbk格式代替utf-8,避免在解码过程中遇到中文文件名而报错
process = Popen(["cmd"], shell=False, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
commands = (
            "activate lane-det\n"
            "f:\n"
            "cd F:/unity download/installs location/2021.3.11f1c2\Editor/New Unity Project\Assets/lane-python/Ultra-Fast-Lane-Detection-master\n"
            "python video_detect.py configs//tusimple.py --test_model tusimple_18.pth\n"
            )
outs, errs = process.communicate(commands.encode("gbk"))
content = [z.strip() for z in outs.decode("gbk").split("\n") if z]
print(*content,sep="\n")

只替换第七行commands后的语句为逐条的cmd命令(应修改第二句的cd路径到正确的文件夹下,以及video_detect.py和tusimple.py中的路径),将其命名为run-cmd.py,将其存放在configs文件夹下。

3.unity中窗口—>常规—>python console,点击load加载run-cmd.py文件,运行成功

4.编辑c#脚本运行python文件 (将c#脚本挂到物体上,运行时即可调用python)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.Scripting.Python;//添加此行

public class Runpython : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        string path = Application.dataPath + "/lane-python/Ultra-Fast-Lane-Detection-master/configs/run-cmd.py";//在Assets中的路径
        PythonRunner.RunFile(path);//添加这两行的代码
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 挂上脚本之后点击运行,遇到报错pthonexception:gbk‘ codec can‘t decode byte 0xad ......,是字符编码问题,此处选择将run-cmd.py中中文部分删除,报错消除。

此处运行成功

猜你喜欢

转载自blog.csdn.net/weixin_45318827/article/details/127658752