The problem that opencv saves grayscale video but cannot play it

  • When setting cv2.VideoWriter, you need to set the fifth parameter to 0, indicating the grayscale image
    video_writer = cv2.VideoWriter('road_gray.mp4', cv2.VideoWriter_fourcc(*'mp4v'), fps, size, 0)
  • The size of cv2.VideoWriter needs to be the same as the size of the original image, and the format is width*height
# 获得视频的格式
import cv2

videoCapture = cv2.VideoCapture('road.mp4')

# 获得码率及尺寸
fps = videoCapture.get(cv2.CAP_PROP_FPS)
size = (int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)),
        int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
print(size)
video_writer = cv2.VideoWriter('road_gray.mp4', cv2.VideoWriter_fourcc(*'mp4v'), fps, size, 0)

while (videoCapture.isOpened()):
    ret, frame = videoCapture.read()
    if ret == True:
        frame_gray = cv2.cvtColor(frame,cv2.COLOR_RGB2GRAY)
        video_writer.write(frame_gray)
        cv2.imshow('frame', frame_gray)
        if cv2.waitKey(1) & 0xFF == ord('q'):
          break
    else:
        break


videoCapture.release()
video_writer.release()
cv2.destroyAllWindows()

Guess you like

Origin blog.csdn.net/weixin_42173136/article/details/127176419
Recommended