如何在 Python 中缩放和平移图像?
How to Zoom and Pan Image in Python?
我有一张图片:
我想在这张图片上选择一个点。但是,当我显示图像时,我只能在屏幕上看到一部分,如下:
我想知道如何缩小和平移图像,以便我也能够在同一图像上选取一个点并进行处理。
我尝试使用此处给出的代码:Move and zoom a tkinter canvas with mouse 但问题是这会在不同的 canvas 上显示图像,我所有的进一步处理都应该在图像上进行本身。
我不想使用图像调整大小功能,因为这会导致像素变化 orientation/pixel 损失
请帮忙!
您应该在处理图像本身的过程中将 canvas 坐标转换为图像坐标。
例如,对于代码“Move and zoom a tkinter canvas with mouse”,将以下事件添加到 Zoom class 的 __init__
方法中:
self.canvas.bind('<ButtonPress-3>', self.get_coords) # get coords of the image
函数self.get_coords
将鼠标右键单击事件的坐标转换为图像坐标并在控制台打印:
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')
另外,我建议您使用更先进的缩放技术。特别是粗体 EDIT text.
之后的第二个代码示例
我有一张图片:
我想在这张图片上选择一个点。但是,当我显示图像时,我只能在屏幕上看到一部分,如下:
我想知道如何缩小和平移图像,以便我也能够在同一图像上选取一个点并进行处理。
我尝试使用此处给出的代码:Move and zoom a tkinter canvas with mouse 但问题是这会在不同的 canvas 上显示图像,我所有的进一步处理都应该在图像上进行本身。
我不想使用图像调整大小功能,因为这会导致像素变化 orientation/pixel 损失
请帮忙!
您应该在处理图像本身的过程中将 canvas 坐标转换为图像坐标。
例如,对于代码“Move and zoom a tkinter canvas with mouse”,将以下事件添加到 Zoom class 的 __init__
方法中:
self.canvas.bind('<ButtonPress-3>', self.get_coords) # get coords of the image
函数self.get_coords
将鼠标右键单击事件的坐标转换为图像坐标并在控制台打印:
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')
另外,我建议您使用更先进的缩放技术