Python截取屏幕截图并将其保存到缓冲区 [英] Python take a screenshot of the screen and save it to a buffer

查看:96
本文介绍了Python截取屏幕截图并将其保存到缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想截取屏幕截图并将其保存为照片( X.jpg )作为缓冲区,以后我可以使用 cv2(opencv)从缓冲区读取相同的图像.
我的行为如下:

I want to take a screenshot of the screen and save it to a buffer as a photo(X.jpg) and later I can use the cv2(opencv) to read the same image from the buffer.
i act as follow:

from PIL import ImageGrab
from io import BytesIO

ii = ImageGrab.grab()
with BytesIO() as output:
    ii.save(output,format="JPEG")# This line has an error 
    cam = output.getvalue()
result, frame = cv2.imencode('.jpg', cam, encode_param)

我收到此错误消息:

TypeError: img is not a numpy array, neither a scalar

谢谢

推荐答案

这是一个演示:

from PIL import ImageGrab
from io import BytesIO
import numpy as np 
import cv2

## (1) Grab the rgb frame as PIL.Image
ii = ImageGrab.grab()
print(type(ii)) # <class 'PIL.Image.Image'>

## (2) Convert PIL.Image to np.array 
rgb = np.array(ii)
print(type(ii)) # <class 'numpy.ndarray'>

## (3) Convert into BGR and display 
bgr = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
cv2.imshow("frame", bgr)
cv2.waitKey()
cv2.destroyAllWindows()

这篇关于Python截取屏幕截图并将其保存到缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆