简体   繁体   中英

Python OpenCV Error(-215) in VideoWriter.write

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM