Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在文件夹中使用opencv更改视频速度后保存视频?_Python_Python 3.x_Opencv_Save_Video Processing - Fatal编程技术网

Python 如何在文件夹中使用opencv更改视频速度后保存视频?

Python 如何在文件夹中使用opencv更改视频速度后保存视频?,python,python-3.x,opencv,save,video-processing,Python,Python 3.x,Opencv,Save,Video Processing,使用:OpenCV和Python3 我正在使用Python 3.8.2 操作系统:macOS Big Sur 11.2.3 我在VScode上尝试了此代码,它确实使用cv2.imshow命令以更改的速度显示视频,但我不知道如何将更改的视频保存到我的文件夹中: import cv2 cap = cv2.VideoCapture('Pothole testing.mp4') frameTime = 100 while(cap.isOpened()): ret, frame = cap.

使用:OpenCV和Python3

我正在使用Python 3.8.2

操作系统:macOS Big Sur 11.2.3

我在VScode上尝试了此代码,它确实使用
cv2.imshow
命令以更改的速度显示视频,但我不知道如何将更改的视频保存到我的文件夹中:

import cv2
cap = cv2.VideoCapture('Pothole testing.mp4')
frameTime = 100 

while(cap.isOpened()):

    ret, frame = cap.read()
    cv2.imshow('frame',frame)
    if cv2.waitKey(frameTime) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

有谁能告诉我,我应该向这个代码中添加什么以便保存更改的视频吗?最好是.mp4格式本身。

您可以使用该方法的fps参数。fps可以通过将
frameTime
变量除以
1000
来计算,因为
cv2.waitKey()
方法接收数字并将其用作千分之一秒

请注意,如果在
while
循环期间
cap
从未关闭,则
while cap.isOpened()
不会比
while True
更好,这意味着在读取最后一帧时,将发生错误,导致永远不会调用
writer.release()
方法,从而使生成的文件无法读取

我会这样做:

import cv2

cap = cv2.VideoCapture('Pothole testing.mp4')
ret, frame = cap.read() # Get one ret and frame 
h, w, _ = frame.shape # Use frame to get width and height
frameTime = 100

fourcc = cv2.VideoWriter_fourcc(*"XVID") # XVID is the ID, can be changed to anything
fps = 1000 / frameTime # Calculate fps
writer = cv2.VideoWriter("Pothole testing 2.mp4", fourcc, fps, (w, h)) # Video writing device

while ret: # Use the ret to determin end of video
    writer.write(frame) # Write frame
    cv2.imshow("frame", frame)
    if cv2.waitKey(frameTime) & 0xFF == ord('q'):
        break
    ret, frame = cap.read()

writer.release()
cap.release()
cv2.destroyAllWindows()
如果所需的只是结果文件而不是进度窗口,则可以省略几行:

import cv2

cap = cv2.VideoCapture('Pothole testing.mp4')
ret, frame = cap.read()
h, w, _ = frame.shape
frameTime = 100

fourcc = cv2.VideoWriter_fourcc(*"XVID")
fps = 1000 / frameTime
writer = cv2.VideoWriter("Pothole testing 2.mp4", fourcc, fps, (w, h))

while ret:
    writer.write(frame)
    ret, frame = cap.read()

writer.release()
cap.release()

非常感谢。这是有效的,我唯一需要改变的是从XVID到mp4的mp4v。