1. 程式人生 > 實用技巧 >Python使用pillow結合opencv-python錄屏

Python使用pillow結合opencv-python錄屏

pip install numpy opencv-python pillow

import threading
import time

from selenium import webdriver
from PIL import ImageGrab
import numpy as np
import cv2

FPS = 20  # 錄製幀數


def shot(dr):
    screen = ImageGrab.grab()
    height, width = screen.size
    video = cv2.VideoWriter('video.avi', cv2.VideoWriter_fourcc(*'XVID'), FPS, (height, width))
    while True:
        capture = ImageGrab.grab()  # 抓取螢幕
        frame = cv2.cvtColor(np.array(capture), cv2.COLOR_RGB2BGR)
        [video.write(frame) for i in range(15)]  # 一次填15幀相同影象
        try:
            dr.title
        except Exception as ex:
            print(ex)
            break
        # cv2.imshow('imm', np.zeros((200,200), np.uint8))
        # if cv2.waitKey(1) & 0xFF == ord('q'):
        #     break
    video.release()

    # cv2.destroyAllWindows()


dr = webdriver.Chrome()
t = threading.Thread(target=shot, args=(dr,))  # 新建執行緒
t.start()  # 啟動截圖執行緒

dr.get('https://www.baidu.com')
time.sleep(1)
dr.find_element('id', 'kw').send_keys('簡書 韓志超')
dr.find_element('id', 'su').click()
time.sleep(1)
dr.get('https://www.qq.com')
dr.back()
time.sleep(3)
dr.quit()

問題,錄製出的視訊依然像幻燈片一樣。