首页 > 解决方案 > 如何将视频作为输入传递给Android Studio中的python代码

问题描述

我想开发一个可以将视频作为输入的应用程序,然后将该视频传递给 python 代码。我知道有一个名为 Chaquopy 的 python SDK 用于在 android studio 中使用 python 代码。但我不知道如何从 Android Studio 内的 res 文件夹中获取视频并将其传递给 python 代码。我的主要算法是在 python 中,为此我需要将视频作为输入传递。我是安卓工作室的新手。有人可以帮助我吗?

标签: python-3.xandroid-studiochaquopy

解决方案


使用 Chaquopy 时,在 Python 代码中加载文件的最简单方法是将其放在 Python 源代码目录中,而不是 res 目录中。从常见问题解答

如果数据文件与 Python 文件位于同一目录中:

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.

如果数据文件和 Python 文件在不同的目录中,则相应地更改路径。例如,如果 Python 文件是alpha/hello.py,而数据文件是bravo/filename.txt,则将filename.txt上面替换为../bravo/filename.txt

Chaquopy 目前不提供任何可以直接读取视频文件的 Python 包。但是,如果您将mobile-ffmpeg添加到您的项目中,您可以从 Python 调用它以从视频中提取帧,然后您可以随意处理这些帧。

有关完整示例,请参见此处,以下是相关行:

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)
    ...

推荐阅读