python - 在python中将win32ui DataBitmap转换为数组

标签 python arrays image-processing

我想拍摄屏幕截图,而不是将其转换为数组,而不将文件另存为路径中的图像,然后从路径中再次加载它以进行转换:

我想要的是将数据直接转换为数组:

        w = 1920
        h = 1080
        bmpfilenamename = r"path"
        hwnd = win32gui.FindWindow(None, "my_window")
        wDC = win32gui.GetWindowDC(hwnd)
        dcObj=win32ui.CreateDCFromHandle(wDC)
        cDC=dcObj.CreateCompatibleDC()
        dataBitMap = win32ui.CreateBitmap()
        dataBitMap.CreateCompatibleBitmap(dcObj, w, h)
        cDC.SelectObject(dataBitMap)
        cDC.BitBlt((0, 0),(w, h) , dcObj, (0, 0), win32con.SRCCOPY)
        dataBitMap.SaveBitmapFile(cDC, bmpfilenamename) #i want to ignor this phase and directly convert the data to array
        My_array = np.array(#myimg , dtype='float')
        print(array)
        print(array.shape)

我的最终目标是为神经网络预测模型提供快速的屏幕截图流

最佳答案

您可以使用 PIL 将 dataBitMap 转换为 PIL Image 对象,如所示 here .
使用 array = np.asarray(im)im 转换为 NumPy 数组。

像素格式应该是 BGRA。

这是一个代码示例:

import win32gui
import win32ui
import win32con
import numpy as np
from PIL import Image
import cv2  # Used for showing the NumPy array as image

w = 1920
h = 1080
hwnd = win32gui.FindWindow(None, "my_window")
wDC = win32gui.GetWindowDC(hwnd)
dcObj = win32ui.CreateDCFromHandle(wDC)
cDC = dcObj.CreateCompatibleDC()
dataBitMap = win32ui.CreateBitmap()
dataBitMap.CreateCompatibleBitmap(dcObj, w, h)
cDC.SelectObject(dataBitMap)
cDC.BitBlt((0, 0), (w, h), dcObj, (0, 0), win32con.SRCCOPY)

# https://stackoverflow.com/questions/6951557/pil-and-bitmap-from-winapi
bmpinfo = dataBitMap.GetInfo()
bmpstr = dataBitMap.GetBitmapBits(True)
im = Image.frombuffer('RGBA', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'RGBA', 0, 1)

array = np.asarray(im) # Convet to NumPy array

# Show image for testing
cv2.imshow('array', array)
cv2.waitKey()
cv2.destroyAllWindows()

关于python - 在python中将win32ui DataBitmap转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71099868/

相关文章:

python - Python 中的容器列表 : standard list vs numpy array

python - 我想使用 IronPython 绘制 visio 图

python - 使用 xlwt,在达到 xls 行限制时创建一个新工作表

java - 错误 : No enclosing instance of type Main is accessible. 必须使用 Main 类型的封闭实例来限定分配(例如 x.new A() wh

arrays - Swift 中的阿拉伯语文本

python - 在opencv + python中处理帧时实时流被延迟

java - Liferay 和 Alfresco 的任何 PHP 或 Python 替代品?

java - 通过数据报包发送数组的最佳方式是什么?

opencv - 视频处理中改变fps的问题有哪些?

ruby-on-rails - Carrierwave 在生产端通过 "heroku rails console"从 s3 添加图片