Python VideoWriter.write 中的 OpenCV 错误 (-215)

Python OpenCV Error(-215) in VideoWriter.write

我正在尝试编写一个 python3-opencv3 代码来读取彩色视频并将其转换为灰度并将其保存回来。 (尝试练习学习python & opencv)

当我在 ubuntu 工作时,我发现 cv2.VideoCapture isColor 标志不起作用(它只起作用 windows)


import numpy as np
import cv2
cap = cv2.VideoCapture('output.avi')
ret, frame = cap.read()
print('ret =', ret, 'W =', frame.shape[1], 'H =', frame.shape[0], 'channel =', frame.shape[2])
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
height, width = gray.shape[:2]
print(height,width)
cv2.imshow('frame',gray)
FPS= 20.0
FrameSize=(frame.shape[1], frame.shape[0]) 
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out = cv2.VideoWriter('Video_output.avi', fourcc, FPS, (width,height))

while(ret):
    ret, frame = cap.read()
    if cv2.waitKey(1) & 0xFF == ord('q') or ret == False:
        break
    print('ret =', ret, 'W =', frame.shape[1], 'H =', frame.shape[0], 'channel =', frame.shape[2])
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # Save the video
    out.write(gray) 
    cv2.imshow('frame',gray)
cap.release()
out.release()
cv2.destroyAllWindows()

给我这个 错误:(-215) img.cols == width && img.rows == height*3 in function write

我猜,问题出在帧大小和灰度图像转换上,但我无法弄清楚?我尝试了不同的高度和宽度组合,但 none 能够正确执行程序。

有人可以帮忙吗?

根据评论中的要求:

Traceback (most recent call last):
  File "/home/akash/Coded/VideoCode/Test3", line 70, in <module>
    out.write(gray) 
cv2.error: /home/travis/miniconda/conda-bld/conda_1486587069159/work/opencv-3.1.0/modules/videoio/src/cap_mjpeg_encoder.cpp:834: error: (-215) img.cols == width && img.rows == height*3 in function write

OpenCV 错误 -215 表示 "assertion failed"。断言本身列在消息中(短语 "Assertion failed" 本身可能也应该如此;您可以在 OpenCV 的错误跟踪器中打开关于此的票证)。 (更新:my pull request with this change was accepted on 06.03 并于 opencv 3.4.2 发布。)

正如我们可以从断言中推断的那样,它期望帧是 3-color-channel 帧。要制作灰度视频,you need to pass isColor=False to VideoWriter constructor:

out = cv2.VideoWriter('Video_output.avi', fourcc, FPS, (width,height), False)