如何使用opencv实现matplotlib行选择器?

时间:2018-12-19 13:14:24

标签: python opencv matplotlib tkinter-canvas

我想使用cv2.line来选择在图像上绘制的线条,并对它们进行处理。我意识到自己看过matplotlibs picker,甚至找到了一个很好的例子here。当我将tkinter用于GUI时,我将其添加到了MWE中。

示例代码很好用:

import sys
if sys.version_info[0] < 3:
    import Tkinter as Tk
else:
    import tkinter as Tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import numpy as np

root = Tk.Tk()
root.iconify()

x = np.linspace(0, 10, 100)

fig, ax = plt.subplots()
for i in range(1, 10):
    ax.plot(x, i * x + x, picker=5)

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

def on_pick(event):
    event.artist.set_visible(not event.artist.get_visible())
    fig.canvas.draw()

fig.canvas.callbacks.connect('pick_event', on_pick)

root.mainloop()

现在我的代码无法使用OpenCV

import sys
if sys.version_info[0] < 3:
    import Tkinter as Tk
else:
   import tkinter as Tk
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
import cv2

root = Tk.Tk()
root.iconify()

img = np.zeros([100,100,3],dtype=np.uint8)
img.fill(255)
cv2.line(img,(10,10),(60,90),(100,149,237),2)

fig = Figure()
ax = fig.add_subplot(111)
ax.set_aspect('equal')
ax.plot()
ax.imshow(img)

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

def onpick1(event):
    event.artist.set_visible(not event.artist.get_visible())        
    fig.canvas.draw()

fig.canvas.callbacks.connect('pick_event', onpick1)

root.mainloop()

在两个示例中,onpick1都可以通过单击鼠标来打开或关闭行的可见性,但是没有这样做。我的假设是它与绘制方式或绘制线条的方式有关(ax.pltcv2.line)。我会很高兴有任何帮助。谢谢!

0 个答案:

没有答案