如何将RGB视频转换为灰度并保存?

时间:2018-12-21 19:41:40

标签: python opencv video-processing

我正在将rgb视频转换为灰度视频,并通过使用OpenCV 3.4和Python 2将其另存为新视频。但是,存在一些问题。例如,视频变成损坏的灰度视频。稍微修改代码后,我将无法获得灰度视频。还值得一提的是,保存的视频太慢。我认为它的速度约为fps,但我也无法弄清楚。损坏的视频的屏幕截图:

enter image description here

我尝试了一个互联网上人们普遍使用的代码。但是,我没有得到我想要的。这是破坏我的视频的代码。总而言之,我的实际目的是将rgb视频转换为灰度并保存。我该怎么办?

import numpy as np
import cv2

cap = cv2.VideoCapture('example.mp4')

ret, frame = cap.read()
print('ret =', ret, 'W =', frame.shape[1], 'H =', frame.shape[0], 'channel =', frame.shape[2])


FPS= 20.0
FrameSize=(frame.shape[1], frame.shape[0])
fourcc = cv2.VideoWriter_fourcc(*'MJPG')

out = cv2.VideoWriter('Video_output.avi', fourcc, FPS, FrameSize, 0)

while(cap.isOpened()):
    ret, frame = cap.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    frame = gray

    # Save the video
    out.write(frame)

    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
         break

cap.release()
out.release()
cv2.destroyAllWindows()

对于此代码,它还会给出此错误:

OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, 
file /home/deep/opencv/modules/imgproc/src/color.cpp, line 11048
Traceback (most recent call last):
  File "ColorConverter1.py", line 20, in <module>
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.error: /home/deep/opencv/modules/imgproc/src/color.cpp:11048: error: (-215) scn == 3 || scn == 4 in function cvtColor

源代码在这里:https://gist.github.com/vscv/f7ef0f688fdf5e888dadfb8440830a3d

1 个答案:

答案 0 :(得分:0)

它很可能发生在视频的最后,其中cap.read()返回False,而frameNone。您需要先检查该条件,然后再将其提供给cv2.cvtColor

import numpy as np
import cv2

cap = cv2.VideoCapture('example.mp4')

ret, frame = cap.read()
print('ret =', ret, 'W =', frame.shape[1], 'H =', frame.shape[0], 'channel =', frame.shape[2])


FPS= 20.0
FrameSize=(frame.shape[1], frame.shape[0])
fourcc = cv2.VideoWriter_fourcc(*'MJPG')

out = cv2.VideoWriter('Video_output.avi', fourcc, FPS, FrameSize, 0)

while(cap.isOpened()):
    ret, frame = cap.read()

    # check for successfulness of cap.read()
    if not ret: break

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    frame = gray

    # Save the video
    out.write(frame)

    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
         break

cap.release()
out.release()
cv2.destroyAllWindows()