繁体   English   中英

使用 pyplot 在图像上绘制输入点

[英]plot an input point on a image with pyplot

我想用 pyplot 绘制一个图像,并在该图像上绘制一个点。 该点来自 pyplot 中的输入字段。 在这里,我有一段代码,您可以在其中放置一个点,但是在按 Enter 或搜索按钮后,它不会绘制该点。 这是我的代码:

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()

带有下面输入字段的图像图,这是上面代码的输出

但是当我在输入框中输入 900,800 时,我希望它在 x=900 和 y=800 上显示一个点。

我们必须首先使用plt.sca(ax)选择活动轴,为了刷新画布,我们可以使用fig.canvas.draw()fig.canvas.flush_events()

  • fig = plt.imshow(np.flipud(ims), cmap='gray', origin='lower')替换为:

     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
  • plt.plot(x, y, "ro")plt.show()替换为:

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

代码示例:

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM