简体   繁体   中英

How to save video capture in mp4 format with opencv python

Guys I'm capturing the desktop video with opencv with python with the following code:

import numpy as np
import cv2                                           
from mss import mss                                  
from PIL import Image

bounding_box = {'top': 100, 'left': 0, 'width': 400, 'height': 300}

sct = mss()
                                                 
while True:
 sct_img = sct.grab(bounding_box)                     
 cv2.imshow('screen', np.array(sct_img))             
 if(cv2.waitKey(1) & 0xFF) == ord('q'):
  cv2.destroyAllWindows()
  break

I want to be able to save this capture in mp4 format, how can I do this?

It should work something like this.

import numpy as np
import cv2                                           
from mss import mss                                  
from PIL import Image

bounding_box = {'top': 100, 'left': 0, 'width': 400, 'height': 300}

sct = mss()
fourcc = cv2.VideoWriter_fourcc(*'MP4V')
out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (640,480))
                                                
while True:
  sct_img = sct.grab(bounding_box)   
  out.write(np.array(sct_img))                  
  cv2.imshow('screen', np.array(sct_img))             
  if(cv2.waitKey(1) & 0xFF) == ord('q'):
      cv2.destroyAllWindows()
      break

Official documentation shows example in Getting Started with Videos

import numpy as np
import cv2 as cv

cap = cv.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter('output.avi', fourcc, 20.0, (640,  480))

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

    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break

    frame = cv.flip(frame, 0)

    # write the flipped frame
    out.write(frame)

    cv.imshow('frame', frame)

    if cv.waitKey(1) == ord('q'):
        break

# Release everything if job is finished
cap.release()
out.release()
cv.destroyAllWindows()

First you have to set codec using 4-chars code. There is page fourcc.org with codes.

Different systems may use different codecs - mostly DIVX , XVID , MJPG , X264 , WMV1 , WMV2 .

fourcc = cv.VideoWriter_fourcc(*'XVID')

Next you have to set filename with extension, FPS , width, height

out = cv.VideoWriter('output.avi', fourcc, 20.0, (400,  300))

Some codecs not work with some extensions - you may need to check different combinations ( .avi , .mp4 , .mkv , .mov , etc.)

If images have 400x300 and you want video 800x600 then set VideoWriter(..., (800, 600)) but you also have to resize every frames before writing because VideoWriter doesn't resize it automatically - it skip frames (without error) and finally it creates empty file (~4kb).

frame = cv2.resize(frame, (800, 600))

out.write(frame)

VideoWriter(.., 20.0, ...) sets 20 FPS (frames per second) but it is not speed of writing but it is information for video players how fast they have to display it.

If you create 20 frames in every second then player will display it in correct speed. If you create 10 frames in every second then player will display it 2x faster. If you create 40 frames in every second then player will displau it with half speed.


It uses program FFMPEG and you can see list of codecs running in system console/terminal

ffmpeg -codecs

or in source code (with 4-chars codes)

http://ffmpeg.org/doxygen/trunk/isom_8c-source.html

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