Python實(shí)現(xiàn)自動(dòng)化錄制屏幕并生成視頻
本文將展示如何在有另一個(gè)Python進(jìn)程運(yùn)行時(shí),使用Python自動(dòng)錄制屏幕生成視頻,并用以檢查其執(zhí)行情況。
大多數(shù)時(shí)候,當(dāng)需要對(duì)非常老舊的系統(tǒng)進(jìn)行自動(dòng)化時(shí),將不得不通過(guò)GUI來(lái)完成,因?yàn)樗鼈儧](méi)有API,GUI自動(dòng)化可能非常棘手并且會(huì)出現(xiàn)意外行為。
解決這個(gè)問(wèn)題的最好方法是嘗試處理代碼中的每一個(gè)可能的異常,但也可能會(huì)發(fā)生意外錯(cuò)誤。所以當(dāng)發(fā)生異常時(shí),最好保存一個(gè)異常情況的視頻來(lái)以便于分析,并調(diào)試代碼。
使用Python的多進(jìn)程庫(kù),在與運(yùn)行自動(dòng)化的線程不同的線程中,運(yùn)行屏幕錄制腳本。已經(jīng)用三個(gè)不同的庫(kù)測(cè)試了這個(gè)腳本的屏幕錄制:Mss,Pillow,和Pyautogui。在這些庫(kù)中,Mss是表現(xiàn)最好的一個(gè)。
以下是固定時(shí)間錄制的代碼片段:
from time import sleep
from mss.windows import MSS as mss
import multiprocessing
import pyautogui
import cv2
import numpy as np
from os import remove
class FixedTimeCapture:
def __init__(self, capture_time:int, video_path:str='C:/test') -> None:
self.fps = 15
self.capture_time = capture_time
self.video_path = video_path.replace('\\','/') + '.avi'
self.process = multiprocessing.Process(
target=self.capture_screen,
args=(),
name='Screen Capture'
)
def capture_screen(self):
SCREEN_SIZE = tuple(pyautogui.size())
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(self.video_path, fourcc, self.fps, (SCREEN_SIZE))
print(f'Screen capture started')
w, h = pyautogui.size()
monitor = {'top':0, 'left':0, 'width':w, 'height':h}
with mss() as sct:
for i in range(int(self.capture_time * self.fps)):
try:
img = sct.grab(monitor=monitor)
frame = np.array(img)
frame = cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)
out.write(frame)
except IOError:
pass
cv2.destroyAllWindows()
out.release()
sleep(3)
print('Screen capture finished')
def start_capture(self):
self.process.start()
def abort_capture(self):
if not self.process.is_alive():
print('The process is not executing')
else:
print('Aborting screen capture')
self.process.kill()
sleep(3)
try:
remove(self.video_path)
except:
print('Couldnt delete the file')
if __name__ == '__main__':
ct = FixedTimeCapture(capture_time=10, video_path=r'C:\test')
ct.start_capture()
# 如果想中止錄制并在其完成之前刪除文件
# ct = FixedTimeCapture(capture_time=10, video_path=r'C:\test2')
# ct.start_capture()
# sleep(5)
# ct.abort_capture()請(qǐng)注意,其中包含了一個(gè)選項(xiàng)來(lái)中止進(jìn)程并在必要時(shí)刪除文件。使用的是AVI視頻編解碼器,錄制速度為15幀/秒,但可以自行更改這些設(shè)置。
不知道錄制的過(guò)程要花多長(zhǎng)時(shí)間的情況下,可以創(chuàng)建一個(gè)函數(shù)來(lái)開(kāi)始錄制,另一個(gè)函數(shù)來(lái)結(jié)束錄制。
from time import sleep
from mss.windows import MSS as mss
import multiprocessing
import pyautogui
import cv2
import numpy as np
from os import remove
class CaptureScreen:
def __init__(self, video_path:str) -> None:
self.fps = 15
self.video_path = video_path.replace('\\','/') + '.avi'
self.process = multiprocessing.Process(
target=self.capture_screen,
args=(),
name='Screen Capture'
)
def capture_screen(self):
SCREEN_SIZE = tuple(pyautogui.size())
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(self.video_path, fourcc, self.fps, (SCREEN_SIZE))
img = None
print(f'Screen capture started')
# MSS
w, h = pyautogui.size()
monitor = {'top':0, 'left':0, 'width':w, 'height':h}
with mss() as sct:
while True:
try:
try:
img = sct.grab(monitor=monitor)
frame = np.array(img)
frame = cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)
out.write(frame)
except IOError:
pass
except KeyboardInterrupt:
break
cv2.destroyAllWindows()
out.release()
# # PILLOW
# from PIL import ImageGrab
# w, h = pyautogui.size()
# while True:
# try:
# try:
# img = ImageGrab.grab(bbox =(0, 0, w, h))
# frame = np.array(img)
# frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# out.write(frame)
# except IOError:
# pass
# except KeyboardInterrupt:
# break
# cv2.destroyAllWindows()
# out.release()
# # PYAUTOGUI
# while True:
# try:
# try:
# img = pyautogui.screenshot()
# frame = np.array(img)
# frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# out.write(frame)
# except IOError:
# pass
# except KeyboardInterrupt:
# break
# cv2.destroyAllWindows()
# out.release()
def start_capture(self):
self.process.start()
def finish_capture(self):
if not self.process.is_alive():
print('The process is not executing')
else:
self.process.terminate()
sleep(3)
print('Screen capture finished')
if __name__ == '__main__':
c = CaptureScreen(video_path=r'C:\test')
c.start_capture()
sleep(15)
c.finish_capture()在這個(gè)例子中,還包含了Pillow和Pyautogui的實(shí)現(xiàn),如果想進(jìn)行一下測(cè)試,需要調(diào)整幀率以獲得100%完美的視頻再現(xiàn)速度。
到此這篇關(guān)于Python實(shí)現(xiàn)自動(dòng)化錄制屏幕并生成視頻的文章就介紹到這了,更多相關(guān)Python自動(dòng)化錄屏內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python實(shí)現(xiàn)套接字創(chuàng)建
這篇文章主要為大家介紹了python套接字創(chuàng)建實(shí)現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
Python實(shí)現(xiàn)SVN的目錄周期性備份實(shí)例
這篇文章主要介紹了Python實(shí)現(xiàn)SVN的目錄周期性備份,實(shí)例分析了Python實(shí)現(xiàn)SVN周期性備份的原理與實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07
Python實(shí)現(xiàn)簡(jiǎn)易信息分類存儲(chǔ)軟件
這篇文章主要介紹的是通過(guò)Python制作一個(gè)簡(jiǎn)易的文件分類存儲(chǔ)文件,可以實(shí)現(xiàn)信息的增刪改查以及內(nèi)容的導(dǎo)出和回復(fù),文中的示例代碼對(duì)我們的學(xué)習(xí)有一定的價(jià)值,感興趣的同學(xué)可以了解一下2021-12-12
django執(zhí)行原生SQL查詢的實(shí)現(xiàn)
本文主要介紹了django執(zhí)行原生SQL查詢的實(shí)現(xiàn),主要有兩種方法實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08
淺談哪個(gè)Python庫(kù)才最適合做數(shù)據(jù)可視化
數(shù)據(jù)可視化是任何探索性數(shù)據(jù)分析或報(bào)告的關(guān)鍵步驟,目前有許多非常好的商業(yè)智能工具,比如Tableau、googledatastudio和PowerBI等,本文就詳細(xì)的進(jìn)行對(duì)比,感興趣的可以了解一下2021-06-06
Python?Struct庫(kù)之pack和unpack舉例詳解
這篇文章主要給大家介紹了關(guān)于Python?Struct庫(kù)之pack和unpack的相關(guān)資料,pack和unpack在處理二進(jìn)制流中比較常用的封包、解包格式,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-02-02
Python利用PyMuPDF模塊實(shí)現(xiàn)快速轉(zhuǎn)換PDF文件
PDF是一種廣泛使用的文件格式,可以在任何設(shè)備上查看和打印,那么如何用Python和PyMuPDF制作你想要大小的PDF文件呢,本文就來(lái)和大家詳細(xì)講講2023-08-08

