使用Pywin32在内存中裁剪位图图像

时间:2018-05-20 00:03:51

标签: python numpy python-imaging-library pywin32

我正在尝试使用pywin32在多台显示器上截取桌面的屏幕截图。

我在第三台显示器上有我需要的屏幕截图,但我只需要图像的某个区域。

当我将位图图像保存到我的硬盘驱动器时,我能够裁剪它:

# initial set up code hooking up pywin32 to the desktop

import win32gui, win32ui, win32con, win32api
hwin = win32gui.GetDesktopWindow()

# example dimensions
width = 800
height = 600
left = 3300
top = 100

hwindc = win32gui.GetWindowDC(hwin)
srcdc = win32ui.CreateDCFromHandle(hwindc)
memdc = srcdc.CreateCompatibleDC()
bmp = win32ui.CreateBitmap()
bmp.CreateCompatibleBitmap(srcdc, width, height)
memdc.SelectObject(bmp)

# saving of the file (what I am currently doing)
bmp.SaveBitmapFile(memdc, 'fullshot.bmp')

# strangely enough this crops the portion I need, 
# but within an image that's the entire length of my desktop
# (not sure how to fix that, you could say this is part of the problem)
memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY)


img = Image.open('fullshot.bmp')
img = img.crop((0,0,800,600))
# now the cropped image is in memory but I want just the portion I need without saving it to disk

bmp的类型为'PyCBitmap'。我试过np.array(bmp),但这也行不通。有没有办法可以将pmp32截取的bmp截取并将其裁剪到程序存储器中我需要的尺寸?

更新:

我尝试了以下不起作用的代码。当我尝试用cv2.imshow('image', img)显示它时,我得到一个反应迟钝的窗口。

signedIntsArray = bmp.GetBitmapBits(True)
img = np.frombuffer(signedIntsArray, dtype='uint8')
img.shape = (height,width,4)

srcdc.DeleteDC()
memdc.DeleteDC()
win32gui.ReleaseDC(hwin, hwindc)
win32gui.DeleteObject(bmp.GetHandle())

cv2.imshow('image', img)

1 个答案:

答案 0 :(得分:0)

我遇到的问题并不是下面的代码有点不起作用:

signedIntsArray = bmp.GetBitmapBits(True)
img =  np.frombuffer(signedIntsArray, dtype='uint8')
img.shape = (h,w,4)

当我将其作为cv2.imshow发送到cv2.imshow('image', np.array(img)函数时,我意识到我需要设置一个waitKey:

cv2.imshow('image', np.array(screen_grab()))
cv2.waitKey(0)
cv2.destroyAllWindows()

这给了我正在寻找的东西。希望这有助于将来的某些人。