使用Python保存数组中的屏幕截图

2024-04-23 20:23:49 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用python、mss和opencv来捕获我的计算机屏幕并将其保存为图像数组以形成电影?我正在转换成灰度,所以它可以是一个三维数组。我想把每个二维屏幕快照存储在一个三维数组中,以便查看和处理。我很难构建一个数组来保存屏幕截图序列以及在cv2中回放屏幕截图序列。 非常感谢

import time
import numpy as np
import cv2
import mss
from PIL import Image

with mss.mss() as sct:
    fps_list=[]
    matrix_list = []
    monitor = {'top':40, 'left':0, 'width':800, 'height':640}
    timer = 0
    while timer <100:
        last_time = time.time()

        #get raw pizels from screen and save to numpy array
        img = np.array(sct.grab(monitor))
        img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        #Save img data as matrix
        matrix_list[timer,:,:] = img

        #Display Image
        cv2.imshow('Normal', img)
        fps = 1/ (time.time()-last_time)
        fps_list.append(fps)

        #press q to quit
        timer += 1
        if cv2.waitKey(25) & 0xFF == ord('q'):
            cv2.destroyAllWindows()
            break
#calculate fps
fps_list = np.asarray(fps_list)
print(np.average(fps_list))


#playback image movie from screencapture
t=0
while t < 100:
    cv.imshow('Playback',img_matrix[t])
    t += 1

Tags: fromimportimg屏幕timeasnp序列
2条回答

使用collections.OrderedDict()保存序列

import collections
....
fps_list= collections.OrderedDict()
...
fps_list[timer] = fps

一个提示也许是,把截图保存到一个列表中,以后再回放(你必须调整睡眠时间):

import time
import cv2
import mss
import numpy


with mss.mss() as sct:
    monitor = {'top': 40, 'left': 0, 'width': 800, 'height': 640}
    img_matrix = []

    for _ in range(100):
        # Get raw pizels from screen and save to numpy array
        img = numpy.array(sct.grab(monitor))
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        # Save img data as matrix
        img_matrix.append(img)

        # Display Image
        cv2.imshow('Normal', img)

        # Press q to quit
        if cv2.waitKey(25) & 0xFF == ord('q'):
            cv2.destroyAllWindows()
            break

    # Playback image movie from screencapture
    for img in img_matrix:
        cv2.imshow('Playback', img)
        time.sleep(0.1)

相关问题 更多 >