我的代码用于逐帧循环遍历文件中的现有视频,并在将每个图像帧写入新文件之前为每个帧添加一些文本,该文件应该是视频。另外,我在循环中添加这些图像(每次迭代循环时写入文件的一个图像)VS在代码结束时一次写入所有图像。
最终视频与输入视频相同,但上面有一些文字。代码不会崩溃,但输出mp4文件说当我尝试使用我的Mac时,QuickTime无法打开它并且它似乎没有正确写入。这是我的代码:
cap = cv2.VideoCapture('me_ballin.mov')
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Be sure to use lower case
out = cv2.VideoWriter('OUTPUT_PLEASE.mp4', fourcc, 20.0, (640, 640))
while cap.isOpened():
ret, img = cap.read()
font = cv2.FONT_HERSHEY_SIMPLEX
bottomLeftCornerOfText = (100,250)
fontScale = 2
fontColor = (255,255,255)
lineType = 2
photo_text = "BALLINNNN"
cv2.putText(img, photo_text,
bottomLeftCornerOfText,
font,
fontScale,
fontColor,
lineType)
out.write(img)
正如我所说,当我运行代码时,它不会崩溃,但输出文件OUTPUT_PLEASE.mp4无法打开。想法?
答案 0 :(得分:2)
也许您应该将输出大小设置为等于输入的大小。
#!/usr/bin/python3
import cv2
## opening videocapture
cap = cv2.VideoCapture(0)
## some videowriter props
sz = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
fps = 20
#fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
#fourcc = cv2.VideoWriter_fourcc('m', 'p', 'e', 'g')
fourcc = cv2.VideoWriter_fourcc(*'mpeg')
## open and set props
vout = cv2.VideoWriter()
vout.open('output.mp4',fourcc,fps,sz,True)
cnt = 0
while cnt<20:
cnt += 1
print(cnt)
_, frame = cap.read()
cv2.putText(frame, str(cnt), (10, 20), cv2.FONT_HERSHEY_PLAIN, 1, (0,255,0), 1, cv2.LINE_AA)
vout.write(frame)
vout.release()
cap.release()
结果: