已经和这个问题争了一整天,也许有人可以帮忙吗?掌握Mathlab,python和openCV的基础知识 我使用python从图像制作视频。并且,通常,发现它的问题。读取图像时没有用于写视频的顺序。例如,我有img_01,img_02,..... img_n。每个img - 视频帧。最后的视频看起来像是:
./ img_155.jpg ./img_476.jpg ./img_282.jpg 等等。
因此,最终视频完全混乱,结果...... 有这个问题,有人可以帮忙吗?我发现了很多提示,但所有提示只有c ++。有代码,我现在正在使用:
import cv2
import argparse
import os
# Construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-ext", "--extension", required=False, default='jpg', help="extension name. default is 'png'.")
ap.add_argument("-o", "--output", required=False, default='output.mp4', help="output video file")
args = vars(ap.parse_args())
# Arguments
dir_path = '.'
ext = args['extension']
output = args['output']
images = []
for f in os.listdir(dir_path):
if f.endswith(ext):
images.append(f)
# Determine the width and height from the first image
image_path = os.path.join(dir_path, images[0])
frame = cv2.imread(image_path)
cv2.imshow('video',frame)
height, width, channels = frame.shape
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Be sure to use lower case
out = cv2.VideoWriter(output, fourcc, 30.0, (width, height))
for image in images:
image_path = os.path.join(dir_path, image)
frame = cv2.imread(image_path)
out.write(frame) # Write out frame to video
cv2.imshow('video',frame)
if (cv2.waitKey(1) & 0xFF) == ord('q'): # Hit `q` to exit
break
# Release everything if job is finished
out.release()
cv2.destroyAllWindows()
print("The output video is {}".format(output))
答案 0 :(得分:1)
我认为你的问题是:对于os.listdir(dir_path)中的f:以随机顺序返回文件名。
您应该在'#确定第一张图片的宽度和高度之前添加关注行'
def name2num(name):
m = re.search('img_(\d+)\.?.*', name)
return int(m.group(1),10)
images.sort(key=name2num)