How to write simple geometric shapes into numpy arrays

前端 未结 5 1003
名媛妹妹
名媛妹妹 2021-01-30 00:36

I would like to generate a numpy array of 200x200 elements in size and put into it a circle centered into 100,100 coordinates, radius 80 and stroke width of 3 pixels. How to do

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-30 00:48

    One way to do this using only numpy, (similar to @Simon's answer) is as follows:

    import numpy as np
    
    def draw_circle(radius, dim=None):
        if dim == None:
            dim = (radius * 2, radius * 2)
        circle = np.zeros(dim)
        x, y = np.meshgrid(np.arange(dim[0]), np.arange(dim[1]))
        r = np.abs((x - dim[0] / 2)**2 + (y - dim[1] / 2)**2 - radius**2)
    
        m1 = r.min(axis=1, keepdims=True)
        m2 = r.min(axis=0, keepdims=True)
        rr = np.logical_or(r == m1, r == m2)
        l_x_lim = int(dim[0] / 2 - radius)
        u_x_lim = int(dim[0] / 2 + radius + 1)
        l_y_lim = int(dim[0] / 2 - radius)
        u_y_lim = int(dim[0] / 2 + radius + 1)
    
        circle[l_x_lim:u_x_lim, l_y_lim:u_y_lim][rr[l_x_lim:u_x_lim, l_y_lim:u_y_lim]] = 1
        return circle
    
    gen_circle(20) # draw a circle of radius 20 pixels
    

提交回复
热议问题