Nischitha s
Nischitha s

Reputation: 1

How to play the video using opencv in android programatically?

As I'm fresher in android I did the image processing using OpenCV.Now I need to process the video that is I need to play the video using OpenCV. Now I need to play the video in my app using OpenCV I tried using the videocapture class but it's getting an error that provides some implementation.So please help me in playing the video in my app using OpenCV.

Upvotes: 0

Views: 1567

Answers (2)

Rana Ranvijay Singh
Rana Ranvijay Singh

Reputation: 6165

I tried following the steps given by @Kalai. It seems to work. I did not face any errors. Giving the code in the hope it could help someone.

I kept my video file in the raw directory.

enter image description here

override fun onCreate(savedInstanceState: Bundle?) {
        ...
        if (!OpenCVLoader.initDebug())
            Log.e("OpenCV", "Unable to load OpenCV!")
        else
            Log.d("OpenCV", "OpenCV loaded Successfully!")

        val absFilePath = moveFileFromRawToApp()
        openFileByOpenCV(absFilePath)
    }

private fun moveFileFromRawToApp(): String {
    val ins: InputStream = resources.openRawResource(R.raw.marvel)
    val outFile = getAppSpecificDirectory("marvel.mp4")
    val out = FileOutputStream(outFile)
    val outputStream = ByteArrayOutputStream()
    var buffer = ByteArray(1024)
    var size = ins.read(buffer, 0, 1024)
    while (size >= 0) {
        outputStream.write(buffer, 0, size)
        size = ins.read(buffer, 0, 1024)
    }
    ins.close()
    buffer = outputStream.toByteArray()
    out.write(buffer)
    out.close()
    return outFile.absolutePath
}

private fun getAppSpecificDirectory(filename: String): File {
    val file = File(baseContext.filesDir, filename)
    if (!file.exists()) {
        file.createNewFile()
    }
    return file
}

private fun openFileByOpenCV(absFilePath: String) {
    val videoCapture = VideoCapture()
    videoCapture.open(absFilePath)
    Toast.makeText(this, "OpenCV worked", Toast.LENGTH_LONG).show()
}

At the end you will have a video file in your mobile device data > data > [package name] > files > marvel.mp4

enter image description here

Upvotes: 1

Kalai
Kalai

Reputation: 543

Just giving the file name as an argument to the capture.open() wont work here, given that you are working on an android platform.

I took the below steps to resolve my problem, which is similar to yours.

  1. Placed the video file under res/raw.
  2. Copied the video file from res/raw to an app specific directory ( I copied it to an external one, and I did this in a different thread from the UI/main thread )
  3. Used the Absolute path of the recently copied file as the argument, via getAbsolutePath(), in the VideoCapture Constructor or in open(String FileName).

Note: I understand this question was asked 3 years ago; I'm posting this as I think this might be useful for those who stumble upon this issue.

Upvotes: 1

Related Questions