我试图允许用户右键单击图像一次,然后再次,然后程序将从第一次点击到第二次点击一行。
然而,我现在所拥有的,似乎是随机地将线条插入到我的图像中。它们弹出,它们远不及我的点击,并且具有随机的长度和角度。
我是python的初学者,绝对是matplotlib
,所以任何帮助都会受到赞赏。下面是我的代码,相关区域标有一行#s:
from pymouse import PyMouse
import matplotlib.pyplot as plt
import matplotlib.lines as lines
import numpy
im1 = plt.imread('xexample1.PNG')
im2 = plt.imread('xexample2.PNG')
im3 = plt.imread('xexample3.PNG')
data_images = [im1,im2,im3]
index = 0
ax = plt.gca()
fig = plt.gcf()
plt.imshow(data_images[index])
linepoints = numpy.array([])
print linepoints
#on click event- print x,y coords
def onclick(event):
# if event.xdata != None and event.ydata != None:
plot = numpy.asarray(data_images[index])
if event.button == 1:
print("IMAGE: %d" %index, event.xdata, event.ydata,(plot[event.xdata][event.ydata])*255)
######################################################################
if event.button == 3:
global linepoints
x = event.xdata
y = event.ydata
tup1 = [(x, y)]
linepoints = numpy.append(linepoints, x)
linepoints = numpy.append(linepoints, y)
if numpy.size(linepoints) == 4:
# print "full"
#l1 = lines.Line2D([linepoints[0], linepoints[1]], [linepoints[2],linepoints[3]], transform=fig.transFigure, figure=plt)
#fig.canvas.draw()
plt.plot((linepoints[0], linepoints[1]), (linepoints[2], linepoints[3]), '-')
print linepoints
linepoints = numpy.array([])
print linepoints
# plt.show()
######################################################################
def toggle_images(event):
global index
if event.key == 'x':
index += 1
if index < len(data_images) and index >= 0:
plt.imshow(data_images[index])
plt.draw()
else:
#plt.close()
print 'out of range'
index -= 1
if event.key == 'z':
index -= 1
if index < len(data_images) and index >= 0:
plt.imshow(data_images[index])
plt.draw()
else:
#plt.close()
print 'out of range'
index += 1
plt.imshow(data_images[index])
plt.connect('key_press_event',toggle_images)
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
答案 0 :(得分:1)
我在下面创建了一个装扮好的版本,但最后在你的代码中只有一个非常小的错误:
plt.plot((linepoints[0], linepoints[1]), (linepoints[2], linepoints[3]), '-')
需要:
plt.plot((linepoints[0], linepoints[2]), (linepoints[1], linepoints[3]), '-')
即;您的第一个(索引0
)和第三个(索引2
)值是x
值,第二个(索引1
)和第四个(索引3
)是y
值,现在您实际上正在绘制(x0,y0),(x1,y1)
而不是(x0,x1),(y0,y1)
我的最小例子:
import matplotlib.pyplot as plt
import numpy
plt.close('all')
fake_img = numpy.random.random((10,10))
plt.imshow(fake_img, interpolation='none')
ax = plt.gca()
fig = plt.gcf()
linepoints = numpy.array([])
def onclick(event):
if event.button == 3:
global linepoints
x = event.xdata
y = event.ydata
linepoints = numpy.append(linepoints, x)
linepoints = numpy.append(linepoints, y)
if numpy.size(linepoints) == 4:
plt.plot((linepoints[0], linepoints[2]), (linepoints[1], linepoints[3]), '-')
linepoints = numpy.array([])
plt.show()
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()