Как извлечь кадры из файла mp4 в памяти (байтовый буфер) в Python? - PullRequest
1 голос
/ 09 июля 2020

Теперь мое решение извлекает изображения с сохранением байтов на диск с помощью 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

Есть ли какое-либо решение, которое не требуется сохранение потока на диск?

...