如何在 Android Studio 中获取原始资源的文件路径?

App*_*pem 4 android file

我一直在使用教程对图片进行一些人脸检测。问题是当我获取在 java 上使用的文件路径时

String xmlFile = "E:/OpenCV/facedetect/lbpcascade_frontalface.xml";
CascadeClassifier classifier = new CascadeClassifier(xmlFile);
Run Code Online (Sandbox Code Playgroud)

我如何在 android studio 上翻译。我尝试将我的 lbpcascade_frontalface.xml 放在原始资源上。CascadeClassifier 是 opencv 库提供的一个类。唯一的问题是它们只加载了字符串路径(在 xmlfile 上)。这是我的代码。

String pathtoRes = getRawPathAtempt2(context);
CascadeClassifier cascadeClassifier = new CascadeClassifier();
cascadeClassifier.load(pathtoRes);
Run Code Online (Sandbox Code Playgroud)

我翻译成这样的方法。

  public String getRawPathAtempt2(Context context) {
    return "android.resource://" + context.getPackageName() + "/raw/" + "lbpcascade_frontalface.xml";
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我收到 opencv 的断言错误,告诉我文件为空。那意味着当我在我的方法中使用文件路径时我错了。如何获取原始资源的文件路径?请帮帮我我已经被困了好几天了

Com*_*are 6

如何获取原始资源的文件路径?

你不能。没有路径。它是您开发机器上的一个文件。它不是设备上的文件。相反,它是 APK 文件中的一个条目,即您在设备上的应用。

如果您的库支持的InputStream,而不是一个文件系统路径,getResources().openRawResource()Context得到一个InputStream在你的原始资源。