【问题标题】:use win32gui to capture grayscale screen使用win32gui抓拍灰度画面
【发布时间】:2021-10-26 09:35:20
【问题描述】:

我使用以下代码在 python 中捕获窗口屏幕:

def get_screenshot(self):

    # get the window image data
    wDC = win32gui.GetWindowDC(self.hwnd)
    dcObj = win32ui.CreateDCFromHandle(wDC)
    cDC = dcObj.CreateCompatibleDC()
    dataBitMap = win32ui.CreateBitmap()
    dataBitMap.CreateCompatibleBitmap(dcObj, self.w, self.h)
    cDC.SelectObject(dataBitMap)
    cDC.BitBlt((0, 0), (self.w, self.h), dcObj, (self.cropped_x, self.cropped_y), win32con.SRCCOPY)
    
    # convert the raw data into a format opencv can read
    #dataBitMap.SaveBitmapFile(cDC, 'debug.bmp')
    signedIntsArray = dataBitMap.GetBitmapBits(True)
    img = np.fromstring(signedIntsArray, dtype='uint8')
    img.shape = (self.h, self.w, 4)


    # free resources
    dcObj.DeleteDC()
    cDC.DeleteDC()
    win32gui.ReleaseDC(self.hwnd, wDC)
    win32gui.DeleteObject(dataBitMap.GetHandle())

    # drop the alpha channel, or cv.matchTemplate() will throw an error like:
    #   error: (-215:Assertion failed) (depth == CV_8U || depth == CV_32F) && type == _templ.type() 
    #   && _img.dims() <= 2 in function 'cv::matchTemplate'
    img = img[...,:3]

    # make image C_CONTIGUOUS to avoid errors that look like:
    #   File ... in draw_rectangles
    #   TypeError: an integer is required (got type tuple)
    # see the discussion here:
    # https://github.com/opencv/opencv/issues/14866#issuecomment-580207109
    img = np.ascontiguousarray(img)
    return img

我从一些 YouTube 教程中获取了代码,代码运行良好。

但是,我正在尝试将该图像转换为灰度,以便以后可以将其用于 Homography,但没有任何成功。

我尝试使用 cv.cvtColor 之类的东西,但没有任何效果。

有什么方法可以让它在捕捉时变成灰度?

谢谢

【问题讨论】:

  • 您可以通过0.3*R + 0.6*G + 0.11*B将RGB值转换为灰度值。

标签: python windows win32gui


【解决方案1】:

使用 Pillow 包中的 img.convert() 函数转换为灰度样式

from PIL import Image

img = Image.open('download.png')
imgGray = img.convert('L')
imgGray.save('test_gray.png')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 2012-09-03
    • 2016-09-06
    • 1970-01-01
    • 2017-09-01
    • 2015-05-29
    相关资源
    最近更新 更多