如果想在plt.figure的图像上点击以获取图片中某点的坐标,
或者同时显示了几个subplot, 想通过键盘输入数字以选择第几个subplot,
这时就需要加入互动。
下面就以上case来说明如何互动。
1.鼠标点击获取坐标
定义一个onclick函数作为event触发。
这里假设最多可选3个坐标。
在close掉figure的时刻选点互动结束,点击的坐标就作为list的元素保存到coords里。
coords = []
def onclick(event):
global ix, iy
ix, iy = int(event.xdata), int(event.ydata)
print(f'x = {ix}, y = {iy}')
print("If finished, please close the figure.")
global coords
coords.append((ix, iy))
if len(coords) == 3:
fig.canvas.mpl_disconnect(cid)
print("finished! please close the figure.")
return coords
fig = plt.figure()
plt.title("please click the targer, you can click at most 3 points.")
plt.axis("off")
ax = fig.add_subplot(111)
ax.imshow(img)
cid = fig.canvas.mpl_connect("button_press_event", onclick)
plt.show()
input_point = np.array(coords) #list转np array
2.键盘输入
比如现在figure 中subplot 3张图片,想用键盘输入0,1,2,来选择到底用哪张图片。
这时定义onkey event。
close figure时选择结束。键盘输入会保存在select_id变量中。
def onkey(event):
print('you selected id: ', event.key)
global select_id
select_id = int(event.key)
#fig.canvas.mpl_disconnect(cid)
print("if finished, please close the figure.")
return select_id
fig = plt.figure()
plt.title("please select id, key input: 0/ 1/ 2")
plt.axis("off")
ax = fig.add_subplot(131)
ax.imshow(imgs[0])
ax = fig.add_subplot(132)
ax.imshow(imgs[1])
ax = fig.add_subplot(133)
ax.imshow(imgs[2])
cid = fig.canvas.mpl_connect('key_press_event', onkey)
plt.show()