【问题标题】:Return x,y values of a 2D plot with mouse click通过鼠标单击返回 2D 绘图的 x,y 值
【发布时间】:2020-05-18 10:37:58
【问题描述】:
我正在绘制一个简单的图像,并希望获得 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 个 x,y 值的列表。
【问题讨论】:
标签:
python
arrays
matplotlib
click
mplcursors
【解决方案1】:
首先,对于要点击的图像,“png”通常是比“jpg”更合适的格式。用于“jpg”颜色的压缩可能会涂抹颜色。
mplcursors 是一个支持在绘图上单击(或悬停)的小包。标准它显示带有坐标的注释工具提示。在您的应用程序中显示注释工具提示似乎很有用。如果没有,您可以使用 sel.annotation.set_visible(False) 抑制该行为,并且仍然接收带有坐标的事件。
坐标有两种形式:x 和 y 使用轴的坐标系,或者使用索引 (i,j) 来指示像素。使用imshow 的extent= 参数可以灵活设置所需的范围(默认x 和y 从0 到图像的宽度和高度)。每个像素中心的x,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)