簡體   English   中英

將自動位圖轉換為枕頭圖像

[英]Converting an autopy bitmap to a Pillow image

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

是否可以將位圖對象轉換為枕頭圖像對象?

我目前的解決方法是將位圖對象保存為圖片文件,然后使用路徑創建一個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:]))

當我在我的機器上測試時,紅色和藍色通道是向后的,所以我假設來自autopy的位圖是 RGB 編碼的,而不是 BMP 文件使用的典型 BGR 編碼,這是 PIL 所期望的。 最后,使用 PIL 加載圖像:

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

要正常加載圖像而不交換紅色和藍色通道,請執行以下操作:

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

看起來現在這有一個來自 autopy解決方案

import autopy
import PIL.Image

bmp = autopy.bitmap.capture_screen()
width, height = int(round(bmp.width * bmp.scale)), int(round(bmp.height * bmp.scale))
img = PIL.Image.frombytes('RGB', (width, height), bytes(bmp))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM