我正在嘗試從一系列影像創建視頻。下面是我的代碼。
import os
import cv2
mean_width = 6000
mean_height = 4000
def generate_video():
image_folder = 'C:/New folder/Images/q/'
video_name = 'myvideo.avi'
os.chdir("C:/New folder/Images/q/")
images = [img for img in os.listdir(image_folder)
if img.endswith(".jpg") or
img.endswith(".jpeg") or
img.endswith("png")]#I'll use my own function for that, just easier to read
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape
video = cv2.VideoWriter(video_name, 0, 0.25, (width, height))#0.25 so one image is 4 seconds
for image in images:
video.write(cv2.imread(os.path.join(image_folder, image)))
cv2.destroyAllWindows()
video.release()
generate_video()
然而,上面的代碼只用一張圖片創建了視頻。檔案夾 C:/New folder/Images/q/ 中還有 5 個其他影像,但僅為第一個生成視頻。有人可以告知這里是否缺少任何東西嗎?似乎 for 回圈不起作用
uj5u.com熱心網友回復:
要制作視頻,您需要影像具有相同的解析度。如果某些影像具有不同的大小,則會cv2.VideoWriter悄悄地跳過它們而不會出現任何錯誤。
因此,您可能需要將影像大小調整為固定大小:
for image in images:
image = cv2.imread(os.path.join(image_folder, image))
image = cv2.resize(image, (width, height))
video.write(image)
重現此行為的示例:
import cv2
import numpy as np
fc = cv2.VideoWriter_fourcc(*"mp4v")
video = cv2.VideoWriter("1.mp4", fc, 0.25, (500, 500))
for idx in range(10):
color = np.random.randint(0, 255, size=3)
if idx in [0, 2, 3]: # only 3 frames will be in the final video
image = np.full((500, 500, 3), fill_value=color, dtype=np.uint8)
else:
# slighly different size
image = np.full((400, 500, 3), fill_value=color, dtype=np.uint8)
video.write(image)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/519709.html
標籤:Pythonopencv
