Search code examples
python-3.xandroid-studiochaquopy

How to pass video as input to python code inside Android Studio


I want to develop an application that can take video as input and then pass that video to the python code. I know that there is a python SDK named Chaquopy for using python code inside android studio. But I don't know how to take video from res folder inside Android Studio and pass that to python code. My main algorithm is in python and for that I need to pass video as input. I'm new to android Studio. Can someone help me in this.


Solution

  • When using Chaquopy, the easiest way to load a file in Python code is to put it in the Python source code directory, not the res directory. From the FAQ:

    If the data file is in the same directory as the Python file:

    from os.path import dirname, join
    filename = join(dirname(__file__), "filename.txt")
    You can then pass the filename to open, or any other function which reads a file.
    

    If the data file and the Python file are in different directories, then change the path accordingly. For example, if the Python file is alpha/hello.py, and the data file is bravo/filename.txt, then replace filename.txt above with ../bravo/filename.txt.

    Chaquopy doesn't currently provide any Python packages which can read video files directly. However, if you add mobile-ffmpeg to your project, you can call it from Python to extract the frames from the video, which you can then process however you like.

    See here for a full example, and here are the relevant lines:

    from com.arthenica.mobileffmpeg import FFmpeg
    ...
    FFmpeg.execute("-i " + path + " -r " + frame_gap + " -f image2 " + initial_path + "/image-%2d.png")
    image_read_counter = 1
    while image_read_counter < int(vid_length_in_seconds * frame_gap):
        str_image_read_counter = '%02d' % image_read_counter
        image_path = initial_path + '/image-' + str_image_read_counter + '.png'
        img = cv2.imread(image_path)
        ...