0

I'm trying to write a program that takes a screenshot of a given window and displays it in imshow. Whenever I run the following code, it displays a black image of the correct size. Please be nice as I'm still very new to openCV

#Imports
import numpy as np
import cv2
import pytesseract
from PIL import ImageGrab
import win32gui


#Assign Tesseract and other Variables
winList = []
toplist = []
pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
lH = 33
lW = 20

#Window Handle Object
def enum_win(hwnd, result):

    winText = win32gui.GetWindowText(hwnd)

    winList.append((hwnd, winText))

win32gui.EnumWindows(enum_win, toplist)


typeHwnd = 0

#Find Window Handle
for (hwnd, winText) in winList:

    if winText == "Program WinText Name Here":
        typeHwnd = hwnd
if typeHwnd == 0:
    print("Oops no Window Found")


while True:
    position = win32gui.GetWindowRect(typeHwnd)

    mid = (position[0] + (position[0] + position[2]))/2

    sPos = (int(mid) - 267, position[1] + 295, (int(mid) - 267) + lW, (position[1] + 295) + lH)

    screenshot = ImageGrab.grab(bbox=sPos)
    screenshot = np.array(screenshot)

    cv2.imshow("Screen", screenshot)
    key = cv2.waitKey(25)

Output:

enter image description here

Alex Rumer
  • 43
  • 1
  • 8
  • what is `screenshot.shape`? after making the numpy array – Epsi95 Feb 09 '21 at 17:07
  • That's not just a pure black image, there is some dark content in there. – couka Feb 09 '21 at 17:49
  • I don't think you can directly set a PIL Image (ImageGrab.grab returns a PIL Image) as a numpy array and give it to opencv. Try this answer to convert from PIL to OpenCV https://stackoverflow.com/questions/14134892/convert-image-from-pil-to-opencv-format – Ian Chu Feb 09 '21 at 23:30

0 Answers0