Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Video corrupted when grayscale applied

I try to convert a video in grayscale with the following code :

import cv2
import numpy as np
# video from https://www.pexels.com/video/drops-of-liquid-on-a-tray-to-be-use-as-samples-3195394/
cap = cv2.VideoCapture('video.mp4')


# Check if camera opened successfully
if (cap.isOpened()== False):
  print("Error opening video stream or file")
down_width = 1800
down_height = 700
down_points = (down_width, down_height)
#fourcc = cv2.VideoWriter_fourcc(*'mp4v')
#fourcc = cv2.VideoWriter_fourcc(*'X264')
#fourcc = cv2.VideoWriter_fourcc(*'DIVX')

fourcc = cv2.VideoWriter_fourcc(*'MJPG')
#fourcc = cv2.VideoWriter_fourcc(*'avc1')
#fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
out = cv2.VideoWriter('outpy.avi', fourcc, 20, (down_width, down_height))
j=0
jmax=100
while(cap.isOpened()):

  # Capture frame-by-frame
  ret, frame = cap.read()
  j = j + 1
  if ret == True:
    print(j)
    shrinked_down = frame[0:down_height,0:down_width]
    gray = cv2.cvtColor(shrinked_down, cv2.COLOR_BGR2GRAY)
    #cv2.imshow('Frame',gray)
    #cv2.waitKey(0)
    #out.write(shrinked_down) # This is working well
    out.write(gray)
    if j>jmax:
      print("j>jmax")
      break

  else:
    break

# When everything done, release the video capture object
cap.release()
out.release()

print("This is the end")

The video is cropped and cut to 100 frames. Everything go well if I write the color version (out.write(shrinked_down)), but the grayscale image gives corrupted file. Also, I can show the grayscale frame. Do you have an idea of the error?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

VideoWriter has a fifth argument which is isColor, when true as by default it expects RGB frames, setting it to false will get your code to work correctly.

out = cv2.VideoWriter('outpy.avi', fourcc, 20, (down_width, down_height),False)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading