Hello programmers, today we are going to create a program that will work same as screen recorder. Yes it will capture all the screen when you execute the program until you manually exit or if you have given particular time for executing the code. So lets start coding.
Here for running the script we will require some libraries installed in your python
- OpenCV2
- Numpy
- Os
- PyAutoGui
Note: If above libraries are not installed in your machine you will get error so to avoid it simpley install them with pip command as
pip install numpy
pip install pyautogui
Os libriary is automatically get installed while installing python so no need to install it externally
To install OpenCV2 just follow steps given on here
So after installing all required libriaries lets start with coding
import cv2
import numpy as np
import os
import pyautogui
output = "video.avi" ##output file will be saved as "video.avi" in current working directory
img = pyautogui.screenshot()
img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
height, width, channels = img.shape ##saving image info into img.shape
fourcc = cv2.VideoWriter_fourcc(*'mp4v')##saving video
out = cv2.VideoWriter(output, fourcc, 20.0, (width, height))
while(True):
try:
img = pyautogui.screenshot()
image = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
out.write(image)
StopIteration(0.5)
except KeyboardInterrupt:
break
out.release()
cv2.destroyAllWindows()
After this make sure you have saved file as screen_recorder.py. Now open terminal and navigate to the folder where you saved your .py file. As I saved my file in SolutionsTouch Folder my terminal looks like
After navigation just execute the file with the command python screen_recorder.py and wait for some time or do whatever you want to record from screen. After your work done just simply press Ctrl + C to stop program execution.
Note: Ctrl + C work as keyboard interruption for code
When you interrupt the execution program will break and stop execution. After this you will get a file named “video.avi”. This is output generated after execution of our program. Just play the .avi file in appropriate video player to make sure you have recorded the screen correctly.
The complete code and sample video output is uploaded so just hit the Download button to download screen_recorder.py and sample output file.
And here we are done..
If any problem persist feel free to comment below to let us know problem you facing while executing the code we will try to get you as soon as possible.
Happy coding :) :)