首页 > 解决方案 > 无法在 python open cv 上使用此代码库录制视频

问题描述

尝试在 python 中使用 opencv 录制视频,我使用 videowrite() 方法录制来录制视频,但我显示错误。此错误显示“需要一个整数(类型为 noneType)”。需要针对此错误的解决方案。

import numpy as np
import os
import cv2

filename = 'video.avi'
frames_per_sec = 24.0
my_res = '720p'

def change_res(cap,width,height):
    cap.set(3,width)
    cap.set(4,height)

STD_DIMENSIONS= {
    "480p": (640, 480),
    "720p": (1280, 720),
    "1080p": (1920, 1080),
    "4k": (3840, 2160),
}
def get_dims(cap, res = '1080p'):
    width, height = STD_DIMENSIONS['480p']
    if res in STD_DIMENSIONS:
        width, height = STD_DIMENSIONS[res]
        change_res(cap,width,height)
        return width,height
VIDEO_TYPE = {
    'avi' : cv2.VideoWriter_fourcc(*'XVID'),
    'mp4' : cv2.VideoWriter_fourcc(*'XVID'),
}

def get_video_type(filename):
    filename, ext  = os.path.splitext(filename)
    if ext in VIDEO_TYPE:
        return VIDEO_TYPE[ext]
        return VIDEO_TYPE['avi'] 

cap = cv2.VideoCapture(0)
dims = get_dims(cap,res=my_res)
video_type_cv2 = get_video_type(filename)

out = cv2.VideoWriter(filename,video_type_cv2,frames_per_sec,dims)

while(True):
    ret, frame = cap.read()
    out.write(frame)
    cv2.imshow('frame',frame)
    if cv2.waitkey(20) & 0xFF == ord('q'):
        break

cap.release()
out.release()
cv2.destroyAllWindows()

输出

Traceback (most recent call last):
  File "video.py", line 40, in <module>
    out = cv2.VideoWriter(filename,video_type_cv2,frames_per_sec,dims)
TypeError: an integer is required (got type NoneType)
[ WARN:0] terminating async callback

标签: pythonopencvcv2

解决方案


您正在使用os.path.splitext.get_video_type

# filename = 'video.avi'
filename, ext  = os.path.splitext(filename)
# Now filename = 'video' , and ext = '.avi'

您期望ext = 'avi'哪些未处理get_video_type并返回None。这是函数文档的链接。


推荐阅读