Python OpenCV Error(-215) in VideoWriter.write

穿精又带淫゛_ 提交于 2019-12-24 09:59:08

问题


I am trying to a write a python3-opencv3 code to read the color video and convert it to grayscale and save it back. (Trying exercises to learn python & opencv)

As I am working in ubuntu, I found out cv2.VideoCapture isColor flag will not work (it works only 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()

It is give me this error: (-215) img.cols == width && img.rows == height*3 in function write

I am guessing, the problem is with framesize and grayscale image conversion but I am not able to figure out ? I have tried different combination of height & widht but none are able execute the program correctly.

Can someone help ?

As requested in the comments:

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:


OpenCV error -215 means "assertion failed". The assertion itself is listed in the message (the phrase "Assertion failed" itself probably should, too; you can open a ticket about this in OpenCV's bug tracker). (Update: my pull request with this change was accepted on 06.03 and was released in opencv 3.4.2.)

As one can deduce from the assertion, it expects the frame to be a 3-color-channel one. To make a grayscale video, you need to pass isColor=False to VideoWriter constructor:

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


来源:https://stackoverflow.com/questions/48976002/python-opencv-error-215-in-videowriter-write

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!