'How do I crop a video steam that's already been resized?

I'm using PILs ImageGrab function to capture an application window in real-time for image detection with OpenCV. I've managed to scale the captured window down to increase the speed of image detection. However, I'm getting a number of false positives I can't seem to avoid. I actually only need to capture a small section of the window 761 34 1142 68

while True:
    # Grab PSS Window and find size 
    window = pygetwindow.getWindowsWithTitle('App')[0]
    x1 = window.left
    y1 = window.top
    height = window.height
    width = window.width
    x2 = x1 + width
    y2 = y1 + height
    # Actual Video Loop, cropped down to the specific window,
    # resized to 1/2 size, and converted to BGR for OpenCV
    haystack_img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
    (width, height) = (haystack_img.width // 2, haystack_img.height // 2)
    haystack_img_resized = haystack_img.resize((width, height))
    
    ########### Line in Question ##############
    haystack_img_cropped = haystack_img_resized[761: 34, 1142:68]

    haystack_img_np = np.array(haystack_img_cropped) 
    haystack = cv.cvtColor(haystack_img_np, cv.COLOR_BGR2GRAY)
    cv.imshow("Screen", haystack)

I tried using OpenCV to slice the image but I get the error:

C:\Users\coyle\OneDrive\froggy-pirate-master\avoidShips>C:/Users/coyle/AppData/Local/Programs/Python/Python39/python.exe c:/Users/coyle/OneDrive/froggy-pirate-master/avoidShips/avoidShipActual/test7.py
Traceback (most recent call last):
  File "c:\Users\test7.py", line 103, in <module>
    objectDetection(ships_to_avoid, 0.92)
  File "c:\Users\test7.py", line 61, in objectDetection
    haystack_img_cropped = haystack_img_resized[761:34, 1142:68]
TypeError: 'Image' object is not subscriptable

And I tried the .crop method:

 haystack_img_resized = haystack_img.resize((width, height))
 haystack_img_resized.crop((761,34,1164,65))
 haystack_img_np = np.array(haystack_img_resized)

which produces no error but hasn't actually cropped anything.

How do I crop my video stream?



Solution 1:[1]

Not sure why, but loading the cropped image into a variable and using that variable worked.

crop = haystack_img_resized.crop((761,34,1164,65))
haystack_img_np = np.array(crop)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ouflak