This works on a normal window but in a fullscreen game this is returning a black screen so I changed the dtype = numpy.uint8 to dtype = numpy.uint16 and now I'm getting the this error. I think it has something to do with the 4 in the tuple.
File "C:\Users\phpjunkie\Python\test_debug\testing\test12.py", line 22, in CaptureWwindow
output.shape = (height, width, 4)
^^^^^^^^^^^^
ValueError: cannot reshape array of size 12288000 into shape (1600,3840,4)
Here is the code:
import phpjunkie.Win32 as Win32
import cv2 as cv
import numpy
import win32gui
import win32ui
import win32con
def CaptureWwindow(hwnd: int):
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
width, height = right - left, bottom - top
wdc = win32gui.GetWindowDC(hwnd)
dc = win32ui.CreateDCFromHandle(wdc)
cdc = dc.CreateCompatibleDC()
bitmap = win32ui.CreateBitmap()
bitmap.CreateCompatibleBitmap(dc, width, height)
cdc.SelectObject(bitmap)
cdc.BitBlt((0, 0), (width, height), dc, (0, 0), win32con.SRCCOPY)
output = numpy.frombuffer(bitmap.GetBitmapBits(True), dtype = numpy.uint16)
output.shape = (height, width, 4)
dc.DeleteDC()
cdc.DeleteDC()
win32gui.ReleaseDC(hwnd, wdc)
win32gui.DeleteObject(bitmap.GetHandle())
return output
hwnd = Win32.GetWindowHandle(partial = 'Marvel\'s Spider-Man Remastered')
screenshot = CaptureWwindow(hwnd)
screenshot = (screenshot >> 2).astype(numpy.uint8)
cv.imshow('screenshot', screenshot)
print(screenshot.dtype)
print(screenshot.shape)
cv.waitKey()
I saw someone else's code and saw three lines that needed to be added that gave me what I wanted and that was to get a screenshot of the game itself and not a screenshot of the desktop.
The only problem I found with his code is the
win32gui.GetClientRect(hwnd)instead ofwin32gui.GetWindowRect(hwnd)was generating all zeros.