尝试在黑框内绘制白色圆圈时出错

2024-06-26 13:29:54 发布

您现在位置:Python中文网/ 问答频道 /正文

这段代码提供了一个黑盒子,里面有一个白色的圆圈,我得到一个错误,我把它添加到代码下面 我正在尝试使用matplotlib在黑框内绘制一个白色圆圈,使用以下代码:

class Circle:
    def __init__(self, resolution, radius, position):
        self.resolution = resolution
        self.radius = radius
        self.position = (position[0], position[1])
        self.output = []
    
    def draw(self):
        box = np.zeros((self.resolution, self.resolution))
        s = (self.radius * 2, self.radius * 2)
        xv, yv = np.meshgrid(np.arange(s[0]), np.arange(s[1]))
        r = np.abs((xv) ** 2 + (yv) ** 2 - self.radius ** 2)
        self.output = np.ones(r)
        circumference_cir = self.output
        return (circumference_cir)
    
    def show(self):
        image = self.output
        plt.imshow(image)


obg = Circle(resolution= 16, radius= 2, position= (2,4))
obg.draw()
obg.show()

我有一个错误:

       1 obg = Circle(resolution= 16, radius= 2, position= (2,4))
 ----> 2 obg.draw()
       3 obg.show()
 

 ---> 16         self.output = np.ones(r)
     17         circumference_cir = self.output
     18         return (circumference_cir)
 

 --> 192     a = empty(shape, dtype, order)
     193     multiarray.copyto(a, 1, casting='unsafe')
     194     return a
 
 TypeError: only integer scalar arrays can be converted to a scalar
 index.

我猜数组到数组的转换有问题 名单,但我不确定。我应该只使用numpy库


Tags: 代码selfoutputreturndefshownpposition
1条回答
网友
1楼 · 发布于 2024-06-26 13:29:54

代码中的np.ones行被错误调用(np.ones需要一个size元组,而不是一个大数组)。相反,尝试用以下内容替换ones行:

self.output = r<0

这应该取r<0的所有点,即半径内的所有点,并将它们设置为1,将所有其他点设置为0

相关问题 更多 >