1

I want to plot an image with pyplot and on top of that image a point. That point is from an input field in the pyplot. Here I have a piece of code, where you can put a point in, but after pressing enter, or search button it won't plot the point. Here is my code:

import cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import TextBox

def imshow_rgb(img_bgr):
    img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
    plt.imshow(img_rgb)

ims = cv2.imread('plattegrondtekening.png', 1)
fig = plt.imshow(np.flipud(ims), cmap='gray', origin='lower')
plt.subplots_adjust(bottom=0.2)

initial_text = ""
x,y=[500,500]

def submit(text):
    x,y = list(map(int,text.split(",")))
    print(x,y)
    plt.plot(x, y, "ro")
    plt.show()
    
axbox = plt.axes([0.1, 0.05, 0.8, 0.075])
text_box = TextBox(axbox, 'search', initial=initial_text)
text_box.on_submit(submit)

plt.show()

image plot with input field below, this is the output of the code above

But I want that it shows a point on x=900 and y=800, when I enter 900,800 in the input box.

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36

1 Answers1

0

We have to select the active axes first using plt.sca(ax) and for refreshing the canvas we may use fig.canvas.draw() and fig.canvas.flush_events().

  • Replace fig = plt.imshow(np.flipud(ims), cmap='gray', origin='lower') with:

     fig = plt.figure()  # Keep the figure for later usage.
     ax = plt.gca()  # Keep the axes for later usage.
     ax.imshow(np.flipud(ims), cmap='gray', origin='lower')  # Show the image on axes ax
    
  • Replace plt.plot(x, y, "ro") and plt.show() with:

     plt.sca(ax)  # Set active axes
     plt.plot(x, y, "ro")
     fig.canvas.draw()  # Refresh the canvas.
     fig.canvas.flush_events()
    

Code sample:

import cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import TextBox

ims = cv2.imread('plattegrondtekening.png', 1)
fig = plt.figure()  # Keep fig for later usage
ax = plt.gca()  # https://stackoverflow.com/questions/25505341/how-to-get-the-axesimages-from-matplotlib
ax.imshow(np.flipud(ims), cmap='gray', origin='lower')
plt.subplots_adjust(bottom=0.2)

initial_text = ""
x,y=[500,500]

def submit(text):
    x, y = list(map(int,text.split(",")))
    print(x,y)
    plt.sca(ax)  # https://stackoverflow.com/questions/19625563/matplotlib-change-the-current-axis-instance-i-e-gca
    plt.plot(x, y, "ro")
    fig.canvas.draw()  # https://stackoverflow.com/questions/4098131/how-to-update-a-plot-in-matplotlib
    fig.canvas.flush_events()
    
axbox = plt.axes([0.1, 0.05, 0.8, 0.075])
text_box = TextBox(axbox, 'search', initial=initial_text)
text_box.on_submit(submit)
plt.show()
Rotem
  • 30,366
  • 4
  • 32
  • 65