Skip to content

Instantly share code, notes, and snippets.

@damascenodiego
Created May 22, 2019 15:58
Show Gist options
  • Save damascenodiego/79fd490efbc456511ff9524bcc0bc149 to your computer and use it in GitHub Desktop.
Save damascenodiego/79fd490efbc456511ff9524bcc0bc149 to your computer and use it in GitHub Desktop.
Capture video data from screen in Python
import cv2
import numpy as np
import os
import pyautogui
# Capture video data from screen in Python
# https://stackoverflow.com/questions/35097837/capture-video-data-from-screen-in-python
output = "video.avi"
img = pyautogui.screenshot()
img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
#get info from img
height, width, channels = img.shape
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(output, fourcc, 20.0, (width, height))
while(True):
try:
img = pyautogui.screenshot()
image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
out.write(img)
StopIteration(0.5)
except KeyboardInterrupt:
break
out.release()
cv2.destroyAllWindows()
@sin-nt
Copy link

sin-nt commented Jun 6, 2020

Hello
I was really searching for a way to record my screen with python until i found you're code.
So thank you for you're code.
I have a question this code records my screen faster than in should and i don't know how to fix it i wanted to know if you can help me on this .
That would be lovely if you could give us a brief explanation on how this code works.
Thank you so much.

@damascenodiego
Copy link
Author

damascenodiego commented Jun 6, 2020

Hi @sin-nt

The truth is that I used this code for a very short time and the ideas behind it are not fresh in my mind.
But let's see how I can help you... :)

As far as I can remember, my idea was to use the OpenCV library to record a video from the screen of a computer I did not have root access or either permission to install more sophisticated tooling support.
These screenshots were taken from using the pyautogui library, as you see in Line 4.

The main part of this code is shown in Line 16 where I create a VideoWriter object to record the screenshots in .avi format.

The parameters for this VideoWriter object can be seen in the OpenCV documentation and they're pretty good and easy to read.

If there is something wrong with the speed of your recorded video it may be something related to the FPS of your VideoWriter object or the speed you are taking the snapshots in the while-loop.

I hope it helps you on your task.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment