Python OpenCV录屏显示

OpenCV录屏显示

import cv2
import numpy as np
import win32api
import win32gui
import win32ui
import win32con
#  获取显示器尺寸
width = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
height = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)
print(width, height)


#  创建设备描述表
hDC = win32gui.GetDC(0)
dcObj = win32ui.CreateDCFromHandle(hDC)
memDC = dcObj.CreateCompatibleDC()
screenshot = win32ui.CreateBitmap()
screenshot.CreateCompatibleBitmap(dcObj, width, height)
memDC.SelectObject(screenshot)

#  录屏循环
while True:
    #  拷贝屏幕到设备描述表中
    memDC.BitBlt((0, 0), (width, height), dcObj, (0, 0), win32con.SRCCOPY)

    #  转换Bitmap到OpenCV格式
    img = np.fromstring(screenshot.GetBitmapBits(True), dtype='uint8')
    img.shape = (height, width, 4)
    print(img)
    #  转换RGBA格式到BGRA格式
    # img = cv2.cvtColor(img, cv2.COLOR_RGBA2BGRA)

    #  显示录屏
    cv2.imshow('Screen', img)

    #  检查键盘输入
    if cv2.waitKey(1) == ord('q'):
        break

#  释放资源
cv2.destroyAllWindows()
memDC.DeleteDC()
win32gui.ReleaseDC(win32con.NULL, hDC)

效果

Python OpenCV录屏显示_第1张图片

你可能感兴趣的:(python,opencv,开发语言)