使用Python PIL和Windows API的活动窗口截图:如何处理圆角?

Nor*_*hts 16 python windows screenshot rounded-corners python-imaging-library

对于这个项目,我正在使用Windows API截图(处理多屏幕)并将其转换为PIL图像; 如果需要的话,我会在窗户周围添加一个阴影.

我的问题是,截图实际上是窗口的矩形; 意思是我在圆角周围捕捉它背后的背景,我不希望这样.我google了很多,发现文档和tuts围绕透明度,我猜我应该找到一种方法来获得窗口的形状,以使其成为我将应用于(矩形)图像的掩码我拿到.但是我现在发现了那个面具.有人可以帮忙吗?

以下是我的代码:

hwnd = win32gui.GetForegroundWindow()

l, t, r, b = win32gui.GetWindowRect(hwnd)
w = r - l
h = b - t

hwndDC = win32gui.GetWindowDC(hwnd)
mfcDC  = win32ui.CreateDCFromHandle(hwndDC)
saveDC = mfcDC.CreateCompatibleDC()

saveBitMap = win32ui.CreateBitmap()
saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
saveDC.SelectObject(saveBitMap)

saveDC.BitBlt((0, 0), (w, h),  mfcDC,  (0, 0),  win32con.SRCCOPY)

#add cursor
if showcursor:
    curFlags, curH, (curX, curY) = win32gui.GetCursorInfo()
    saveDC.DrawIcon((curX, curY), curH)

#load into PIL image
"""http://stackoverflow.com/questions/4199497/image-frombuffer-with-16-bit-image-data"""
bmpinfo = saveBitMap.GetInfo()
bmpstr = saveBitMap.GetBitmapBits(True)
im = Image.frombuffer(
    'RGB',
    (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
    bmpstr, 'raw', 'BGRX', 0, 1)

win32gui.DeleteObject(saveBitMap.GetHandle())
saveDC.DeleteDC()
mfcDC.DeleteDC()
win32gui.ReleaseDC(hwnd, hwndDC)

return im
Run Code Online (Sandbox Code Playgroud)

下面是蓝色背景上方窗口的略微放大的屏幕截图:

正如你所看到的那样,蓝色的角落应该不存在.

Ant*_*mud 1

为什么不使用边缘检测算法(fe Prewitt 或 Sobel)来检测窗口边缘,只需将 alpha 通道设置为图像限制和窗口边缘限制之间的像素即可。