How to write simple geometric shapes into numpy arrays

前端 未结 5 924
名媛妹妹
名媛妹妹 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 01:03

    Another possibility is to use scikit-image. You can use circle_perimeter for a hollow or circle for a full circle.

    You can draw a single stroke circle like so:

    import matplotlib.pyplot as plt
    from skimage import draw
    arr = np.zeros((200, 200))
    rr, cc = draw.circle_perimeter(100, 100, radius=80, shape=arr.shape)
    arr[rr, cc] = 1
    plt.imshow(arr)
    plt.show()
    

    You can also emulate a stroke by using a loop. In this case you should use the anti-aliased version to avoid artifacts:

    import matplotlib.pyplot as plt
    from skimage import draw
    arr = np.zeros((200, 200))
    stroke = 3
    # Create stroke-many circles centered at radius. 
    for delta in range(-(stroke // 2) + (stroke % 2), (stroke + 1) // 2):
        rr, cc, _ = draw.circle_perimeter_aa(100, 100, radius=80+delta, shape=arr.shape)
        arr[rr, cc] = 1
    plt.imshow(arr)
    plt.show()
    

    A probably more efficient way is to generate two full circles and "subtract" the inner from the outer one:

    import matplotlib.pyplot as plt
    from skimage import draw
    arr = np.zeros((200, 200))
    stroke = 3
    # Create an outer and inner circle. Then subtract the inner from the outer.
    radius = 80
    inner_radius = radius - (stroke // 2) + (stroke % 2) - 1 
    outer_radius = radius + ((stroke + 1) // 2)
    ri, ci = draw.circle(100, 100, radius=inner_radius, shape=arr.shape)
    ro, co = draw.circle(100, 100, radius=outer_radius, shape=arr.shape)
    arr[ro, co] = 1
    arr[ri, ci] = 0
    plt.imshow(arr)
    plt.show()
    

    The two methods yield in fact slightly different results.

提交回复
热议问题