How to Zoom and Pan Image in Python?

Question:

I have an image: Image

I wish to pick a point on this image. However, when I display the image, I can only see a part of it on the screen, as follows: Image visible on screen

I wish to know how to zoom out and pan the image in a way that I am able to also pick a point on the same image and do the processing.

I tried to use the code given here : Move and zoom a tkinter canvas with mouse but the problem is that this displays the image on a different canvas, and all of my further processing is supposed to be on the image itself.

I do not want to use the image resize function because that leads to change in pixel orientation/pixel loss

Kindly help!

Asked By: snelzb

||

Answers:

You should convert canvas coordinates to image coordinates during processing the image itself.

For example, for to the code “Move and zoom a tkinter canvas with mouse” add the following event to the __init__ method of the Zoom class:

self.canvas.bind('<ButtonPress-3>', self.get_coords)  # get coords of the image

Function self.get_coords convert coordinates of right mouse button click event to the image coordinates and print them on console:

def get_coords(self, event):
    """ Get coordinates of the mouse click event on the image """
    x1 = self.canvas.canvasx(event.x)  # get coordinates of the event on the canvas
    y1 = self.canvas.canvasy(event.y)
    xy = self.canvas.coords(self.imageid)  # get coords of image's upper left corner
    x2 = round((x1 - xy[0]) / self.imscale)  # get real (x,y) on the image without zoom
    y2 = round((y1 - xy[1]) / self.imscale)
    if 0 <= x2 <= self.image.size[0] and 0 <= y2 <= self.image.size[1]:
        print(x2, y2)
    else:
        print('Outside of the image')

Also I advise you to use more anvanded zoom technique from here. Especially the 2nd code example after bold EDIT text.

Answered By: FooBar167