0

我正在绘制一个简单的图像,并希望获得 x,y 值,我用鼠标单击。

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

image = Image.open('points.jpg')

data = np.array(image)

plt.imshow(data)
plt.show()

带有 4 个点的图像

因此,我可以将鼠标导航到每个点,单击并在最后获得一个包含 4 个 x,y 值的列表。

4

1 回答 1

1

首先,对于要点击的图像,“png”通常是比“jpg”更合适的格式。用于“jpg”颜色的压缩可能会涂抹颜色。

mplcursors是一个支持在绘图上单击(或悬停)的小包。标准它显示带有坐标的注释工具提示。在您的应用程序中显示注释工具提示似乎很有用。如果没有,您可以使用坐标抑制该行为sel.annotation.set_visible(False)并仍然接收带有坐标的事件。

坐标有两种形式:使用轴的坐标系,或使用索引x来指示像素。使用's参数,您可以灵活设置所需的范围(默认值,从 0 到图像的宽度和高度)。每个像素的中心是整数值。因此,您可以将索引或附加到您的列表中。y(i,j)imshowextent=xyx,y(i,j)(x,y)

一些实验代码:

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import mplcursors

image = Image.open('points.png')
data = np.array(image)
img = plt.imshow(data)

points = []

cursor = mplcursors.cursor(img, hover=False)
@cursor.connect("add")
def cursor_clicked(sel):
    # sel.annotation.set_visible(False)
    sel.annotation.set_text(
        f'Clicked on\nx: {sel.target[0]:.2f} y: {sel.target[1]:.2f}\nindex: {sel.target.index}')
    points.append(sel.target.index)
    print("Current list of points:", points)

plt.show()
print("Selected points:", points)
于 2020-02-02T13:21:07.763 回答