plt figure中加入键盘鼠标互动

本文介绍了如何在Matplotlib的plt.figure中实现鼠标点击获取图像坐标的功能,以及如何通过键盘输入选择subplot。主要展示了两个案例:鼠标点击最多选择3个点,以及在包含多个subplot的图中通过键盘输入选择子图。
摘要由CSDN通过智能技术生成

如果想在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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值