使用Python和Pycharm创建一个屏幕录像机
在本教程中,我们将学习如何使用Python包来创建屏幕录像机。然后,我们将进一步将网络摄像头记录器整合到我们的软件中。使用Windows、macOS或Linux的人可以跟随学习。
简介
屏幕录像机是一种捕捉计算机屏幕上发生的内容和活动的软件。这个软件在创建视频教程、记录屏幕内容、供将来参考(做笔记)等活动中至关重要。
在录制教程时,你可能想使用网络摄像头,这样你的听众就能看到你,这能创造一个令人难忘的互动环节。这就导致了屏幕录像机具有网络摄像头录制功能。
说到价格,这种软件有些并不讨巧。还有一些错过了我们想要使用的一些特定功能。
Python作为一种编程语言,有一些软件包可以帮助我们创建自己的屏幕录像机。这可以帮助我们添加我们打算使用的功能,并抛弃我们不需要的功能。
前提条件
要想跟上这篇文章,你应该。
- 熟悉Python编程语言。
- 在你的电脑上安装了pycharm。
我们将使用的Python包
为了创建我们的屏幕录像机,我们将需要以下Python软件包。
- Datetime:我们将需要这个包来知道屏幕录像开始和结束的确切时间。
- Python图像库:我们将需要这个包来捕捉屏幕上的图像。
- Numpy:我们将需要这个包来把我们的图像转换为数组,以便把它传递给open cv。
- win32api:我们将需要这个包来捕捉屏幕的分辨率。
- cv2:我们将需要这个包,以便能够将我们捕获的图像以视频格式保存到我们的文件资源管理器中。
创建一个屏幕记录器并将其与网络摄像头记录器结合起来
我们必须在Pycharm中准备我们的工作空间。打开Pycharm应用程序。一旦打开,点击新项目,如下面的截图所示。然后在接下来出现的窗口中点击创建。

我们现在要把上面讨论的软件包安装到Pycharm中。按照下面的步骤来安装它们。
要安装DateTime,在终端键入以下命令。
pip install DateTime

等待几秒钟,Datetime就会被陆续安装。
我们将对其余的软件包重复同样的步骤。只是命令会有变化。
对各自的软件包使用下面的命令。
numpy
pip install numpy
win32api
pip install pywin32
cv2
pip install opencv-python
Python图像库
pip install Pillow
现在我们的工作区已经准备好了,让我们开始编码。
import datetime
from PIL import ImageGrab
import numpy as ny
import cv2
from win32api import GetSystemMetrics
height = GetSystemMetrics(1) # passing 1 and getting the screen height
width = GetSystemMetrics(0) # passing 0 and getting the screen width
time_stamp = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S') # Getting the exact time the screen is being recorded
file_name = f'{time_stamp}.mp4' # Getting a new value based on the time fo screen recording
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') # Declaring our encoding format
final_video = cv2.VideoWriter(file_name, fourcc, 20.0, (width, height))
# Integrating our webcam to the screen recorder
webcam = cv2.VideoCapture(0) # specifying we will be using the primary camera of our laptop
while True:
img = ImageGrab.grab(bbox=(0, 0, width, height)) # Declaring a variable called img and call ImageGrab to take a picture of our screen
img_ny = ny.array(img) # convert our image to a numpy array in order to pass it to open cv
img_final = cv2.cvtColor(img_ny, cv2.COLOR_BGR2RGB) # cv2 will take our image and convert it to RGB color
_, frame = webcam.read() # opening the webcam
fr_height, fr_width, _ = frame . shape # Finding the width, height and shape of our webcam image
img_final[0:fr_height, 0: fr_width, :] = frame[0:fr_height, 0: fr_width, :] # setting the width and height properties
cv2.imshow('Section screen capture', img_final) # Calling cv2 to display our converted image
final_video.write(img_final) # Writing our converted image
if cv2.waitKey(10) == ord('t'): # waiting for any key that the user will press. If t is pressed the program terminates.
break
结果
下面是代码将产生的输出的截图。

注意:录制的视频将被保存在你的主文件夹下,文件夹名为Pycharm项目。
总结
我们已经建立了一个屏幕录像机,并将其与网络摄像头录像机集成。现在运行你的软件,享受你的新屏幕录像机吧。