首页 文章

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

提问于
浏览
1

我正在尝试编写一个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

我猜,问题是帧大小和灰度图像转换,但我无法搞清楚?我尝试了不同的高度和宽度组合,但没有一个能够正确执行程序 .

有人可以帮忙吗?

按照评论的要求:

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

1 回答

  • 0

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

    正如可以从断言中推断出的那样,它期望帧是3色通道的 . 要制作灰度视频,you need to pass isColor=False to VideoWriter constructor

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

相关问题