python - 如何在Python中缩放和平移图像?

标签 python image tkinter zooming tkinter-canvas

我有一张图片:Image

我想在这张图片上选取一个点。但是,当我显示图像时,我只能在屏幕上看到它的一部分,如下所示:Image visible on screen

我想知道如何缩小和平移图像,以便我也能够在同一图像上选取一个点并进行处理。

我尝试使用此处给出的代码:Move and zoom a tkinter canvas with mouse但问题是,这会在不同的 Canvas 上显示图像,而我所有的进一步处理都应该在图像本身上进行。

我不想使用图像调整大小功能,因为这会导致像素方向/像素丢失的变化

请帮忙!

最佳答案

您应该在处理图像本身时将 Canvas 坐标转换为图像坐标。

例如,对于代码“Move and zoom a tkinter canvas with mouse”,将以下事件添加到 Zoom 类的 __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')

我还建议您使用更先进的缩放技术from here 。特别是粗体 编辑 文本后的第二个代码示例。

关于python - 如何在Python中缩放和平移图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48983027/

相关文章:

image - 对通过在图像内容上运行MD5生成随机图像的唯一文件名有任何警告吗?

python - 我的代码另一个错误

python - 无限循环使 Tkinter 崩溃

Python Tkinter 应用程序在 Mac OS X 上导致 fork()/exec() 错误

python - Hashlib:在 md5.update() 中使用的 block 的最佳大小

python - 如何将字符串列表转换为数字 numpy 数组?

java - 绿色像素的颜色无效

laravel - 在本地存储图像 vs cloudinary vs s3

python - 使用 Tesseract 时出现符号查找错误

python - Pandas 数据框/Python : How to update dataframe cell value using for loop at each iteration in python?