0

In my app,I've the below code:

object FaceDetection {

    private val faceModel = "haarcascade_frontalface_default.xml"

    private lateinit var faceCascade: CascadeClassifier

    fun loadModel(activity: Activity) {
        faceCascade = CascadeClassifier(File(activity.filesDir, "das").apply { writeBytes(activity.assets.open(faceModel).readBytes()) }.path)
    }
}

Which is fail with the above mentioned error, I saved 2 copies from the xml file, one in the xml folder and one in main/java folder, but none of them is working, where shall I put this file, and how to call it if there is something wrong in my call above?

enter image description here UPDATE

I tried solving it as:

    private fun loadModel(activity: Activity) {
        var res = activity.resources
        faceModel = res.getXml(R.xml.haarcascade_frontalface_default).text
        faceCascade = CascadeClassifier(File(activity.filesDir, "das").apply {
            writeBytes(activity.assets.open(faceModel).readBytes())
        }.path)
    }

But got an error:

res.getXml(R.xml.haarcas…frontalface_default).text must not be null
Hasan A Yousef
  • 22,789
  • 24
  • 132
  • 203
  • 1
    Possible duplicate of [Reading a XML file from resources](https://stackoverflow.com/questions/8665712/reading-a-xml-file-from-resources) – Tejashwi Kalp Taru Sep 23 '19 at 11:05
  • 1
    `activity.assets.open(faceModel).readBytes()` is wrong, in that you do not have an asset. [`getXml()` returns an `XmlResourceParser`](https://developer.android.com/reference/android/content/res/Resources#getXml(int)), and `getText()` on an `XmlResourceParser` does not return the text of the XML. Perhaps you will be better served my moving this XML into [an actual asset](https://stackoverflow.com/a/18302624/115145) and going back to your original code snippet. – CommonsWare Sep 23 '19 at 11:33

1 Answers1

0

The solution was to create assets folder under the main folder, and move the file to it, then I was able to read it as:

object FaceDetection {

    private val faceModel = "haarcascade_frontalface_default.xml"

    private lateinit var faceCascade: CascadeClassifier

    fun loadModel(activity: Activity) {
        faceCascade = CascadeClassifier(File(activity.filesDir, "das").apply { writeBytes(activity.assets.open(faceModel).readBytes()) }.path)
    }
}
Hasan A Yousef
  • 22,789
  • 24
  • 132
  • 203