【问题标题】:Python take a screenshot of the screen and save it to a bufferPython 截取屏幕截图并将其保存到缓冲区
【发布时间】:2018-12-17 17:36:06
【问题描述】:

我想截取屏幕截图并将其作为照片保存到缓冲区 (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

谢谢

【问题讨论】:

  • 通过这个link
  • 您能解释一下问题所在并显示您收到的任何错误消息吗? python中的cmets也以#开头,而不是//
  • 我编辑了我的问题
  • 如果你已经将它以JPEG格式保存到磁盘,为什么不直接将文件的内容读入缓冲区(而不是通过imread解码然后用imencode编码回来)?或者更好的是,将 PIL 图像转换为 numpy 数组是 trivial。然后直接imencode,而不是往返文件系统。

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


【解决方案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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-03
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多