# Python – How to write simple geometric shapes into numpy arrays

geometryimagenumpypython

I would like to generate a numpy array of 200×200 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 this in python 2.7 without involving file operations? Possibly using geometry or imaging libraries to allow generalisation to other shapes.

#### Best Solution

The usual way is to define a coordinate mesh and apply your shape's equations. To do that the easiest way is to use `numpy.mgrid`:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.mgrid.html

``````# xx and yy are 200x200 tables containing the x and y coordinates as values
# mgrid is a mesh creation helper
xx, yy = numpy.mgrid[:200, :200]
# circles contains the squared distance to the (100, 100) point
# we are just using the circle equation learnt at school
circle = (xx - 100) ** 2 + (yy - 100) ** 2
# donuts contains 1's and 0's organized in a donut shape
# you apply 2 thresholds on circle to define the shape
donut = numpy.logical_and(circle < (6400 + 60), circle > (6400 - 60))
``````