PIL imagegrab().grab().crop(...) crops not the given coordinates

544 Views Asked by At

I´m creating a canvas on which I draw a number. Then I make a screenshot via the Pillow package and crop it in a way, only the drawn number remains. (Purpose is to predict the drawn number via a CNN) When cropping the screenshot done by the Pillow function imagegrab().grab().crop(...) not the given coordinates in the .crop() are being used. For testing purposes, I tried to manually choose the part of the screenshot which should be cropped by giving crop() some coordinates. When doing so, it works if I choose the upper left corner, but gets more skewed and skewed when I move the part-to-be-cropped more to the right or lower. In the attached Image you can see an example of the cropping performed by the attached code where only a part of the canvas to be cropped had been cropped, additionally with some background

Code to crop a part of the canvas-widget from the screenshot:

def get_drawing():
    widget = cv
    x = root.winfo_rootx() + widget.winfo_x()
    y = root.winfo_rooty() + widget.winfo_y()
    x1 = x + widget.winfo_width()
    y1 = y + widget.winfo_height()

    ImageGrab.grab().crop((x, y, x1, y1)).save("test.png")
2

There are 2 best solutions below

0
MMpythonmm On

I just found the answer to my own question: The issue laid in the monitor I chose to display my canvas. I´m working with a Microsoft Surface attached to a docking station with an external monitor. When I change the display settings to only use the external monitor, the cropping works with the code above as intended. When I use my Surface and extend the display with the external monitor, the cropping gets skewed as shown in the screenshot.

0
Sandeep On

I had the same issue, but in my case the screen was scaled to 125% in windows settings. After changing it to 100% the crop was correct.