0

I have a 2d numpy array and would like to increase the values of a specific part of it by 1. A simple example is:

Empty array:

[[0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]]

We decide to base our area on e.g. 3 points ( [[0,2], [2,4], [3,1]] ) but the number of points could be higher as well:

[[0 0 1 0 0]
 [0 0 0 0 0]
 [0 0 0 0 1]
 [0 1 0 0 0]
 [0 0 0 0 0]]

And fill the shape within this polygone with ones:

[[0 0 1 0 0]
 [0 0 1 1 0]
 [0 1 1 1 1]
 [0 1 1 0 0]
 [0 0 0 0 0]]

How can I do this in an automated way? Something like:

arr = np.zeros([5,5])
shapePoints = [[0,2], [2,4], [3,1]]
valueToFill = 1
arr = fillShape(arr, shapePoints, valueToFill)

... where fillShape is the function that I am searching for. That must exist in numpy?

4
  • Whether the number of vertices you are trying to fill is fixed (Vertices:Three, Shape:Triangle in this case) or can it change in the future? Commented Apr 23, 2019 at 12:44
  • Yes, it can change - minimum of 3 and maximum of possibly 20 or so Commented Apr 23, 2019 at 12:46
  • Have you tried Cairo, I do not know exactly why you want this, but cairo allows creating surfaces. cairographics.org Commented Apr 23, 2019 at 12:52
  • It is in the end not so much about the plotting but about creating the values of the np array ... I can plot all my shapes using PolygonPatch but I want to map them onto an np array in order to do further calculations on them Commented Apr 23, 2019 at 12:57

1 Answer 1

2

Scikit has a implementation for such a polygon drawing algorithm. See skimage.draw.polygon

Edit: concrete code for the question

from skimage.draw import polygon, polygon_perimeter
import numpy as np
arr = np.zeros((5, 5))
shapePoints = np.array([[0,2], [2,4], [3,1]])
points_r, points_c = shapePoints[:, 0], shapePoints[:, 1]
interior_r, interior_c = polygon(points_r, points_c)
perimeter_r, perimeter_c = polygon_perimeter(points_r, points_c)
arr[perimeter_r, perimeter_c] = 3
arr[points_r, points_c] = 2
arr[interior_r, interior_c] = 1    

Note that this produces a different result than the one in the question in order to illustrate the difference between interior and perimeter.

>>> arr
array([[0., 0., 2., 0., 0.],
       [0., 0., 1., 3., 0.],
       [0., 3., 1., 1., 2.],
       [0., 2., 3., 0., 0.],
       [0., 0., 0., 0., 0.]])
Sign up to request clarification or add additional context in comments.

3 Comments

please consider adding the solution here, for the benefit of everyone
That would be just copy-pasting the documentation example. Is that encouraged here?
better than not having anything, IMO :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.