Reputation: 51
I'm trying to do an exercise of an application windows capture using pywin32, so that I get the exact mirror image of the window(like a video game) The issue is - the below code keep capturing/ keep returning only the first frame/old frame of the window and not the current frame of the window. So there is no change reflecting in the mirror image. I tried changing the pywin32 different version but same problem. Please help is there any issue with the lines of code
Python Version== 3.8.10 pywin32 == 227 Windows 10
import cv2 as cv
import numpy as np
from time import time
import win32gui, win32ui, win32con
def get_screenshot(win_name):
hwnd = win32gui.FindWindow(None, win_name)
print('hwnd',hwnd)
window_rect = win32gui.GetWindowRect(hwnd)
print('window_rec',window_rect)
w = window_rect[2] - window_rect[0]
h = window_rect[3] - window_rect[1]
wDC = win32gui.GetWindowDC(hwnd)
print('wDC',wDC)
dcObj = win32ui.CreateDCFromHandle(wDC)
print('dcObj',dcObj)
cDC = dcObj.CreateCompatibleDC()
print('cDC',cDC)
dataBitMap = win32ui.CreateBitmap()
print('dataBitMap',dataBitMap)
dataBitMap.CreateCompatibleBitmap(dcObj, w, h)
cDC.SelectObject(dataBitMap)
cDC.BitBlt((0, 0), (w, h), dcObj, (0,0), win32con.SRCCOPY)
signedIntsArray = dataBitMap.GetBitmapBits(True)
img = np.fromstring(signedIntsArray, dtype='uint8')
img.shape = (h, w, 4)
dcObj.DeleteDC()
cDC.DeleteDC()
win32gui.ReleaseDC(hwnd, wDC)
win32gui.DeleteObject(dataBitMap.GetHandle())
img = img[...,:3]
return img
loop_time = time()
while(True):
# get an updated image of the window
frame = get_screenshot("<<Window Name>>")
cv.imshow('Computer Vision', frame)
# debug the loop rate
#print('FPS {}'.format(1 / (time() - loop_time)))
loop_time = time()
# press 'q' with the output window focused to exit.
# waits 1 ms every loop to process key presses
if cv.waitKey(1) == ord('q'):
cv.destroyAllWindows()
break
Upvotes: 2
Views: 1343
Reputation: 11
I had the same issue, following the same online tutorial. He covers this issue in the 5th video. see here: https://www.youtube.com/watch?v=7k4j-uL8WSQ&list=PL1m2M8LQlzfKtkKq2lK5xko4X-8EZzFPI&index=5
Instead of:
hwnd = win32gui.FindWindow()
use:
hwnd = win32gui.GetDesktopWindow()
Which unfortunately has the side effect of capturing the whole desktop window, but functions great still.
Upvotes: 1