我想使用IPython(Python 2.7)将PPM图像制作成视频。
我编写了以下代码:
import cv2
import glob
img1 = cv2.imread('C:/Users/Joseph/image0.ppm')
height, width, layers = img1.shape
video1 = cv2.VideoWriter('video1.avi', -1, 1, (width, height))
filenames = glob.glob('C:/Users/Joseph/*.ppm')
for filename in filenames:
print(filename)
img = cv2.imread(filename)
video1.write(img)
cv2.destroyAllWindows()
video1.release()
视频已创建,但空的
size=0B
,无法打开。没有错误提示信息。
我怀疑问题出在位置的书写上,因为
print(filename)
输出的是:
而不是我所期望的 :C:/Users/Joseph\image0.ppm
C:/Users/Joseph\image1.ppm
C:/Users/Joseph\image2.ppm
C:/Users/Joseph\image2.ppm
C:/Users/Joseph/image0.ppm
请帮忙确认一下。编辑:文件类型是
type: GIMP 2.10.14 (.ppm)
。这个类型的ppm是否有关?编辑2:看来问题与
.ppm
格式无关。import cv2
import glob
i = cv2.imread('C:/Users/Joseph/image0.ppm')
cv2.imwrite('C:/Users/Joseph/image.jpg',i)
img1 = cv2.imread('C:/Users/Joseph/image.jpg')
height, width, layers = img1.shape
# Set FOURCC code to '24BG' - '24BG' is used for creating uncompressed raw video
video1 = cv2.VideoWriter('video1.avi', cv2.VideoWriter_fourcc('D','I','B',' '), 1, (width, height))
filenames = glob.glob('C:/Users/Joseph/*.ppm')
try:
for filename in filenames:
print(filename)
img = cv2.imread(filename)
cv2.imwrite('C:/Users/Joseph/a.jpg',img)
img=cv2.imread('C:/Users/Joseph/a.jpg')
# Display input image for debugging
cv2.imshow('img', img)
cv2.waitKey(1000)
video1.write(img)
except:
print('An error occurred.')
cv2.destroyAllWindows()
video1.release()
这也不起作用。我也没有看到任何图像显示。
所以看起来这是由于我的cv2视频出现了错误。jpg文件已经成功创建了。
编辑:解决方案。
根据rotem的回答,我尝试了cv2.VideoWriter_fourcc('M','J','P','G')
,它奏效了!