如何优化从PyCBitmap到OpenCV图像的转换 [英] How to optimize conversion from PyCBitmap to OpenCV image
问题描述
我有这段代码,它可以工作...但是运行速度很慢:
I've got this bit of code, and it works... But it runs very slow:
hwin = win32gui.GetDesktopWindow()
width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)
hwindc = win32gui.GetWindowDC(hwin)
srcdc = win32ui.CreateDCFromHandle(hwindc)
memdc = srcdc.CreateCompatibleDC()
bmp = win32ui.CreateBitmap()
bmp.CreateCompatibleBitmap(srcdc, width, height)
memdc.SelectObject(bmp)
memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY)
signedIntsArray = bmp.GetBitmapBits(False)
img = np.array(signedIntsArray).astype(dtype="uint8") # This is REALLY slow!
img.shape = (height,width,4)
srcdc.DeleteDC()
memdc.DeleteDC()
win32gui.ReleaseDC(hwin, hwindc)
win32gui.DeleteObject(bmp.GetHandle())
return cv2.cvtColor(img, cv2.COLOR_RGBA2RGB)
此代码将捕获整个Windows桌面(均显示),并将其转换为我以后使用的OpenCV映像.我认为,如果进行一些重新设计,此转换的运行速度可能会慢一些.具体来说,np.array(signedIntsArray)调用的确很慢!
This code grabs the entire windows desktop (both displays) and converts it to an OpenCV image that I use later. I believe this conversion is running slower than it could, if it was reworked a little. Specifically, the np.array(signedIntsArray) call is really slow!
有人想到如何更快地将桌面捕获转换为OpenCV图像吗?
Any thoughts on how to be a bit faster at converting a desktop capture into an OpenCV image?
推荐答案
首次使用Python.我想我对数据结构现在有了更好的了解.这是可以大大提高性能的解决方案:
First time working with Python. I think I have a better understanding of now of the data structures. Here's the fix that drastically improves performance:
更改:
signedIntsArray = bmp.GetBitmapBits(False)
img = np.array(signedIntsArray).astype(dtype="uint8")
收件人:
signedIntsArray = bmp.GetBitmapBits(True)
img = np.fromstring(signedIntsArray, dtype='uint8')
速度大大提高了!
这是因为np库从字符串创建数组比从元组创建数组要快得多.
This is because it's a lot faster for the np library to create an array from a string than from a tuple.
这篇关于如何优化从PyCBitmap到OpenCV图像的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!