Python截取屏幕截图并将其保存到缓冲区

时间:2018-12-17 17:36:07

标签: python opencv buffer python-imaging-library screenshot

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

编辑我的代码:

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

谢谢

1 个答案:

答案 0 :(得分:1)

这是一个演示:

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()