How to record your screen using Python 🐍
- OpenCV: To install OpenCV, run
pip install opencv-python
- PyAutoGui: To install PyAutoGui, run
pip install pyautogui
- Numpy: To install Numpy, run
pip install numpy
import cv2 #OpenCV import pyautogui import numpy as np
fourCC. It is a 4-byte code used for specifying the video codec. For the sake of simplicity we can pass the
FourCCcode for AVI video format which is
codec = cv2.VideoWriter_fourcc(*"XVID")
videoWriterobject. The video writer method of
cv2module needs 4 mandatory arguments. First is the
filename, second being the
codec, third being the FPS (Frame per second) and the last being the video (or Screen) resolution. For a better screen recording, 60 FPS is a good frame rate. You can experiment around the FPS value to get the optimum results.
out = cv2.VideoWriter("Recorded.avi", codec , 60, (1366, 768)) #Here screen resolution is 1366 x 768, you can change it depending upon your need
namedWindow()method with the
WINDOW_NORMALflag so that the user can resize the window depending upon the need.
cv2.namedWindow("Recording", cv2.WINDOW_NORMAL) cv2.resizeWindow("Recording", 480, 270) #Here we are resizing the window to 480x270 so that the program doesn't run in full screen in the beginning
while True: img = pyautogui.screenshot() #capturing screenshot frame = np.array(img) #converting the image into numpy array representation frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) #converting the BGR image into RGB image out.write(frame) #writing the RBG image to file cv2.imshow('Recording', frame) #display screen/frame being recorded if cv2.waitKey(1) == ord('q'): #Wait for the user to press 'q' key to stop the recording break out.release() #closing the video file cv2.destroyAllWindows() #destroying the recording window
COLOR_BGR2RBGflag. The condition
if cv2.waitKey(1) == ord('q')waits for the user to press ‘q’ key to quit the recording. Lastly, we have closed the video file and destroyed the recording window by
destroyAllWindows()method respectively. PS: Linux users please don’t be happy after hearing “Destroy all Windows”😂 You are all done! It’s time to test the results. Normal-sized window Maximized window: (Horrible infinite loop)
Thanks for reading!
I was making a screen recorder in #python using #opencv and it gave me some weird output😳— Aditya Chaudhary👨💻 (@AdityaGameDev) October 22, 2020
Seems like a portal to any parallel Universe.👁️#100DaysOfCode #codingnewbies #DevCommunityIN #DEVCommunity pic.twitter.com/Z6m3N1IW9N
Did you enjoy reading or think it can be improved? Don’t forget to leave your thoughts in the comments section below! If you liked this article, please share it with your friends, and read a few more!