python - 如何从 Python 中的内存中 mp4 文件(字节缓冲区)中提取帧?
问题描述
现在,我的解决方案使用 OpenCV/FFmpeg 提取图像并在磁盘上保存字节:
from fastapi import APIRouter, UploadFile, File
@router.post("/")
def extract_stream_frames(stream: UploadFile = File(...)):
temp_filename = os.path.join(tempfile.gettempdir(), str(uuid.uuid4()) + ".mp4")
# print(stream.content_type)
local_temp_file = open(temp_filename, "wb")
local_temp_file.write(stream.file.read())
local_temp_file.close()
try:
images = video.sampling(local_temp_file.name, num_frames=Config.IMAGES_PER_STREAM)
images = list(map(lambda array: image.preprocess(array, Config.IMAGE_HEIGHT, Config.IMAGE_WIDTH), images))
result = classify(images=images)
finally:
os.remove(local_temp_file.name)
return result
帧提取功能:
def sampling(video_path: str, num_frames: int):
cam = cv2.VideoCapture(video_path)
images = []
while True:
ret, frame = cam.read()
if ret:
images.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
else:
break
cam.release()
cv2.destroyAllWindows()
total_frames = len(images)
images = [images[frame_no] for frame_no in range(0, total_frames, (total_frames + num_frames -1) // num_frames)]
return images
有没有不需要在磁盘上保存流的解决方案?
解决方案
推荐阅读
- zapier - 使用 Zapier 连接到分页 API?
- python - 乌龟是否有一个按键功能,只重复一次功能
- c - 使用 shellcode 的简单缓冲区溢出漏洞利用不起作用
- python - numpy - 为其右侧满足特定条件的第一个元素创建索引数组
- node.js - MongoDb 查询未按预期运行
- python - 将一个点捕捉到自定义道路网络
- android - 如何从 android 应用程序中的服务器安全地获取凭据?
- firebase - java.lang.RuntimeException:无法在 Flutter 中实例化活动
- php - 无法注册用户,试图在 null 上调用函数 _setnew()
- kotlin - Kotlin 中 Dagger 中带注释的绑定之间的依赖循环