1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| import time import win32gui import win32ui import win32con import cv2 import numpy as np
def videoRecordInit(fps, size, filename): fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter(filename, fourcc, fps, size) return out
def videoRecordWrite(out, frame): out.write(frame)
def videoRecordRelease(out): out.release()
handle = win32gui.FindWindow(None, "应用程序名")
hdc = win32gui.GetDC(handle)
dc = win32ui.CreateDCFromHandle(hdc)
mem_dc = dc.CreateCompatibleDC()
left, top, right, bottom = win32gui.GetWindowRect(handle) width = right - left height = bottom - top
fps = 30
delay = 1 / fps
out = videoRecordInit(fps, (width, height), 'output.mp4')
while True:
bitmap = win32ui.CreateBitmap() bitmap.CreateCompatibleBitmap(dc, width, height)
mem_dc.SelectObject(bitmap)
mem_dc.BitBlt((0, 0), (width, height), dc, (0, 0), win32con.SRCCOPY)
bmp_info = bitmap.GetInfo() bmp_str = bitmap.GetBitmapBits(True) img = np.fromstring(bmp_str, dtype='uint8') img = img.reshape((bmp_info['bmHeight'], bmp_info['bmWidth'], 4))
img = img[:, :, :3]
videoRecordWrite(out, img)
cv2.imshow('frame', img)
time.sleep(delay)
if cv2.waitKey(1) & 0xFF == ord('q'): break
dc.DeleteDC() mem_dc.DeleteDC() win32gui.ReleaseDC(handle, hdc) win32gui.DeleteObject(bitmap.GetHandle()) cv2.destroyAllWindows() videoRecordRelease()
|