【问题标题】:how do I use OpenCV to read video from a NamedTempFile in python如何使用 OpenCV 从 Python 中的 NamedTempFile 读取视频
【发布时间】:2017-10-28 09:24:54
【问题描述】:

我正在尝试从视频中读取帧,但提取帧后视频无用。所以我决定使用 TempFile 模块。但是我使用cv2.VideoCapture(NamedTempFile.name) 获取的框架始终是黑色的。我想知道这是否是正确的方法。如果没有,有没有更好的方法? 我在下面附上了我的代码的视频捕获部分。
我也怀疑 get_temp_video 函数可能是错误的。


def get_temp_video(url, temp_file):
    r = requests.get(url, stream=True)
    for chunk in r.iter_content(chunk_size=1024):
        if chunk:
            temp_file.write(chunk)
    return temp_file


def get_frame(video_url):
    named_temp_file = NamedTemporaryFile()
    named_temp_file = get_temp_video(video_url, named_temp_file)
    named_temp_file.seek(0)
    video = cv2.VideoCapture(named_temp_file.name)
    while video.isOpened():
        ret, frame = video.read()
        if ret:
            temp_file = TemporaryFile()
            np.save(temp_file, frame)
            temp_file.seek(0)
            upload_to_some_where(temp_file.read())
            temp_file.close()
        else:
            break
    video.release()
    named_temp_file.close()

【问题讨论】:

    标签: python opencv video temporary-files


    【解决方案1】:

    我猜问题出在您的函数upload_to_some_where 上,因为其余代码对我来说可以正常工作。出于测试目的,我稍微修改了您的代码:

    def get_temp_video(url, temp_file):
        r = requests.get(url, stream=True)
        for chunk in r.iter_content(chunk_size=1024):
            if chunk:
                temp_file.write(chunk)
        return temp_file
    
    
    def get_frame(video_url):
        named_temp_file = NamedTemporaryFile()
        named_temp_file = get_temp_video(video_url, named_temp_file)
        named_temp_file.seek(0)
        video = cv2.VideoCapture(named_temp_file.name)
        while video.isOpened():
            ret, frame = video.read()
            if ret:
              # For testing purpose
              cv2.imshow("frame", frame)
              if cv2.waitKey(25) == ord('q'):
                break
              ##############################
                # temp_file = TemporaryFile()
                # np.save(temp_file, frame)
                # temp_file.seek(0)
                # upload_to_some_where(temp_file.read())
                # temp_file.close()
            else:
                break
        video.release()
        named_temp_file.close()
    
    if __name__=='__main__':
    
      get_frame('http://samples.mplayerhq.hu/MPEG-4/MPEG4%20by%20philips.mp4')
    

    【讨论】:

    • 感谢您的回答。我发现错误在哪里。就像您的回答一样,upload_to_some_where 函数中的某些逻辑是错误的,
    猜你喜欢
    • 2013-08-21
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多