gpt4 book ai didi

python - 将 autopy 位图转换为 Pillow 图像

转载 作者:太空宇宙 更新时间:2023-11-04 02:36:24 25 4
gpt4 key购买 nike

我正在使用 Autopy 和 Pillow 在 Python 中开发屏幕抓取工具。

是否可以将位图对象转换为 Pillow 图像对象?

我目前的解决方案是将位图对象保存为图像文件,然后使用路径创建一个Pillow图像对象。由于硬盘驱动器 I/O,这种方法真的很慢。

我当前(非常慢)的解决方案:

from PIL import Image
import autopy

bitmap_object = autopy.bitmap.capture_screen()
bitmap_object.save('some/path.png') # VERY SLOW!
img = Image.open('some/path.png')

问题:不将位图对象保存到硬盘是否可以实现上述功能?

最佳答案

查看源代码后,似乎没有办法直接访问原始位图。但是,您可以获得编码副本。

首先,获取其编码表示。

bitmap_encoded = bitmap_object.to_string()

这被编码为“b”,后跟宽度、逗号、高度、逗号和 zlib 压缩原始字节的 base64 编码。解析编码数据:

import base64
import zlib

# b3840,1080,eNrsf...H1ooKAs=
# ^ ^
first_comma = bitmap_encoded.find(',')
second_comma = bitmap_encoded.find(',', first_comma + 1)

# b3840,1080,eNrsf...H1ooKAs=
# ^ ^
width = int(bitmap_encoded[1:first_comma])

# b3840,1080,eNrsf...H1ooKAs=
# ^ ^
height = int(bitmap_encoded[first_comma+1:second_comma])

# b3840,1080,eNrsf...H1ooKAs=
# ^
bitmap_bytes = zlib.decompress(base64.b64decode(bitmap_encoded[second_comma+1:]))

当我在我的机器上测试它时,红色和蓝色 channel 是向后的,所以我假设来自 autopy 的位图是 RGB 编码而不是 BMP 文件使用的典型 BGR 编码太平船务预计。最后,使用 PIL 加载图像:

img = PIL.Image.frombytes('RGB', (width, height), bitmap_bytes, 'raw', 'BGR', 0, 1)

要正常加载图像而不交换红色和蓝色 channel ,请执行以下操作:

img = PIL.Image.frombytes('RGB', (width, height), bitmap_bytes)

关于python - 将 autopy 位图转换为 Pillow 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47797744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com