Reputation: 45
I want to print out the mouse coordinate upon clicking on the displayed image. It is not a graph figure.
After looking through all online forum, I discovered they are all made for a graph figure and not displayed images. I'm surprised I couldn't find even one example.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# The usual way which I found online
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.random.rand(10))
def onclick(event):
print("button=%d, x=%d, y=%d, xdata=%f, ydata=%f" %(
event.button, event.x, event.y, event.xdata, event.ydata))
cid = fig.canvas.mpl_connect('button_press_event', onclick)
# What I currently Have
img = mpimg.imread("my_img.jpg")
plt.imshow(img)
plt.show()
Upvotes: 1
Views: 2656
Reputation: 142641
Matplot uses the same methods to display plot or image. You have to only find figure
for displayed image.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def onclick(event):
print("button=%d, x=%d, y=%d, xdata=%f, ydata=%f" % (
event.button, event.x, event.y, event.xdata, event.ydata))
img = mpimg.imread("image.jpg")
ax = plt.imshow(img)
fig = ax.get_figure()
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
Instead of mpimg.imread()
you can use plt.imread()
Upvotes: 2