Thursday, 5 August 2021

How to generate a chrome playable video in python? videowriter, videoreader

 import cv2
import numpy as np
import subprocess as sp

# writer = cv2.VideoWriter(path, cv2.VideoWriter_fourcc(*"h264"), fps,
#                          (int(width), int(height)))
# for b in buffers:
#     writer.write(b)
# writer.release()

# Create a VideoCapture object
cap = cv2.VideoCapture('input.mp4')

# Check if camera opened successfully
if (cap.isOpened() == False):
  print("Unable to read camera feed")

# Default resolutions of the frame are obtained.The default resolutions are system dependent.
# We convert the resolutions from float to integer.
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))

path = "output.mp4"
FFMPEG_BIN = "ffmpeg" # on Linux ans Mac OS
command = [ FFMPEG_BIN,
    '-y', # (optional) overwrite output file if it exists
    '-f', 'rawvideo',
    '-vcodec','rawvideo',
    '-s', '%dx%d' % (frame_width, frame_height), # size of one frame
    '-pix_fmt', 'bgr24',
    '-r', '15', # frames per second
    '-i', '-', # The input comes from a pipe
    '-an', # Tells FFMPEG not to expect any audio
    '-vcodec', 'h264',
    '%s' % (path) ]

pipe = sp.Popen( command, stdin=sp.PIPE, stderr=sp.PIPE)

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

  if ret == True:
    
    # Write the frame into the file 'output.avi'
    # out.write(frame)
    pipe.stdin.write( frame.tostring() )


    # Display the resulting frame    
    cv2.imshow('frame',frame)

    # Press Q on keyboard to stop recording
    if cv2.waitKey(1) & 0xFF == ord('q'):
      break

  # Break the loop
  else:
    break  

if pipe:
    pipe.stdin.close()
    if pipe.stderr is not None:
        pipe.stderr.close()
    pipe.wait()
    pipe = None
    
# When everything done, release the video capture and video write objects
cap.release()
# out.release()

# Closes all the frames
cv2.destroyAllWindows()