Python 如何在文件夹中使用opencv更改视频速度后保存视频?
使用:OpenCV和Python3 我正在使用Python 3.8.2 操作系统:macOS Big Sur 11.2.3 我在VScode上尝试了此代码,它确实使用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.
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。