Python ginput不允许绘制新点

0 投票
2 回答
2478 浏览
提问于 2025-04-18 08:19

这段代码是让用户通过点击屏幕来选择三个点(使用ginput这个功能),然后应该把这些点显示在图像上面。但是它没有做到这一点。有没有人知道为什么会这样呢?

from pylab import show, ginput, rand, imshow, plot
from matplotlib.figure import Figure
import numpy as np

x1 = rand(103, 53) 
figure = Figure(figsize=(4, 4), dpi=100)
axes = figure.add_subplot(111)

imshow(x1)

# Get user input
x = ginput(3)
x = np.array(x)

# Plot the user's points to the screen
plot(x[:, 0], x[:, 1], 'k*', ms=50)
show()

2 个回答

0

在再次显示图像之前,你可以先关闭之前的图像窗口。

import os, sys
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np

im = np.array(Image.open(sys.argv[1]))
plt.imshow(im)

x = plt.ginput(1)

plt.close()
plt.imshow(im)

plt.plot(x[0][0], x[0][1], 'rs')

plt.show()
1

我不太确定你想要绘制的顺序,是先画星星再画背景,还是先画背景再画星星,但你需要调整一下你的调用顺序。

plot(10, 30, 'k*', ms=100)
x = ginput(2)
imshow(x1)

show()

这样做会先显示一个星星,然后当你点击两个点时,会显示你的随机数据。

这是一个很好的例子,展示了如何使用ginput,具体内容可以在这里找到:

import time
import numpy as np
import matplotlib.pyplot as plt

def tellme(s):
    print(s)
    plt.title(s,fontsize=16)
    plt.draw()

##################################################
# Define a triangle by clicking three points
##################################################
plt.clf()
plt.axis([-1.,1.,-1.,1.])
plt.setp(plt.gca(),autoscale_on=False)

tellme('You will define a triangle, click to begin')

plt.waitforbuttonpress()

happy = False
while not happy:
    pts = []
    while len(pts) < 3:
        tellme('Select 3 corners with mouse')
        pts = np.asarray( plt.ginput(3,timeout=-1) )
        if len(pts) < 3:
            tellme('Too few points, starting over')
            time.sleep(1) # Wait a second

    ph = plt.fill( pts[:,0], pts[:,1], 'r', lw=2 )

    tellme('Happy? Key click for yes, mouse click for no')

    happy = plt.waitforbuttonpress()

    # Get rid of fill
    if not happy:
        for p in ph: p.remove()

撰写回答