Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write simple geometric shapes into numpy arrays

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 this in python 2.7 without involving file operations? Possibly using geometry or imaging libraries to allow generalisation to other shapes.

like image 441
a1an Avatar asked Apr 05 '12 15:04

a1an


People also ask

How do you specify the shape of a NumPy array?

Use the correct NumPy syntax to check the shape of an array. arr = np. array([1, 2, 3, 4, 5]) print(arr. )

What is shape () function in NumPy array used to?

Python numpy shape function The numpy module provides a shape function to represent the shape and size of an array. The shape of an array is the no. of elements in each dimension. In NumPy, we will use a function called shape that returns a tuple, the elements of the tuple give the lengths of the array dimensions.


1 Answers

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)) 
like image 193
Simon Bergot Avatar answered Sep 30 '22 12:09

Simon Bergot