我对这个平台还是个新手.我会尽我所能说清楚的.我的目标是将目录中的帧转换为视频.出于某种原因,它在每15帧中包含第一帧.以下是我的代码:
import cv2
import glob
from pathlib import Path
def play_frames(frames_dir, fps, output_video_path):
# Get the list of frames in the directory
frames = sorted(glob.glob(str(frames_dir / '*.png')))
# Read the first frame to get the width and height
frame = cv2.imread(frames[0])
height, width, _ = frame.shape
# Create the video writer object
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video_writer = cv2.VideoWriter(output_video_path, fourcc, fps, (width, height))
for frame_path in frames:
# Read the frame
frame = cv2.imread(frame_path)
# Display the frame
cv2.imshow('Frame', frame)
cv2.waitKey(int(1000 / fps))
# Write the frame to the video
video_writer.write(frame)
# Release the video writer
video_writer.release()
cv2.destroyAllWindows()
# Directory path
frames_dir = Path('./detected_objects')
fps = 15
output_video_path = 'vid2output.mp4'
# Play the frames and save as video
play_frames(frames_dir, fps, output_video_path)
我在这里try 了无数的代码,但所有的代码(我try 过的)都在每帧每秒添加第一帧.我做错了什么?有没有其他方法可以将图像转换为视频,而不需要在每个fps中添加第一帧?(我已经判断了目录中的帧,它们都是正确的顺序.)
感谢大家的帮助,并乐于提供更多的信息!
最新情况: 我在代码中添加了分辨率大小,但第一帧每秒都显示.
import cv2
import glob
import numpy as np
from pathlib import Path
def play_frames(frames_dir, fps, output_video_path):
# Get the list of frames in the directory
frames = sorted(glob.glob(str(frames_dir / '*.png')))
# Read the first frame to get the width and height
frame = cv2.imread(frames[0])
height, width, _ = frame.shape
# Calculate the maximum width and height among all frames
max_width = width
max_height = height
for frame_path in frames[1:]:
# Read each frame to get its dimensions
frame = cv2.imread(frame_path)
height, width, _ = frame.shape
# Update the maximum width and height if necessary
max_width = max(max_width, width)
max_height = max(max_height, height)
# Create the video writer object
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video_writer = cv2.VideoWriter(output_video_path, fourcc, fps, (max_width, max_height))
# Resize and pad each frame before writing to the video
for frame_path in frames:
frame = cv2.imread(frame_path)
# Resize the frame to the maximum dimensions
resized_frame = cv2.resize(frame, (max_width, max_height))
# Write the resized frame to the video
video_writer.write(resized_frame)
# Release the video writer
video_writer.release()
# Directory path
frames_dir = Path('./detected_objects')
fps = 15
output_video_path = 'vid1output.mp4'
# Play the frames and save as video
play_frames(frames_dir, fps, output_video_path)