1 from timeit import timeit
5 np.set_printoptions(linewidth=500)# hey numpy, take advantage of my large screen
7 def check(p1, p2, base_array):
10 Uses the line defined by p1 and p2 to check array of
11 input indices against interpolated value
13 Returns boolean array, with True inside and False outside of shape
15 idxs = np.indices(base_array.shape) # Create 3D array of indices
20 # Calculate max column idx for each row idx based on interpolated line between two points
21 max_col_idx = (idxs[0] - p1[0]) / (p2[0] - p1[0]) * (p2[1] - p1[1]) + p1[1]
22 sign = np.sign(p2[0] - p1[0])
23 return idxs[1] * sign <= max_col_idx * sign
25 def create_polygon(shape, vertices):
38 return base_array : the resulting matrix
40 Creates np.array with dimensions defined by shape
41 Fills polygon defined by vertices with ones, all other values zero"""
42 base_array = np.zeros(shape, dtype=float) # Initialize your array of zeros
45 fill = np.ones(base_array.shape) # Initialize boolean array defining shape fill
46 # print('timeit (base_array.shape) ', timeit( lambda:np.ones(base_array.shape) ))
47 # print('timeit (base_array.shape) * True ', timeit( lambda:np.ones(base_array.shape) * True ))
48 print('base_array.shape', base_array.shape)
49 print('fill.dtype', fill.dtype)
50 print('fill - 1:', fill)
52 # Create check array for each edge segment, combine into fill array
53 for k in range(vertices.shape[0]):# .shape[0] is the number of vertices, like len(vertices)
54 fill = np.all([fill, check(vertices[k-1], vertices[k], base_array)], axis=0)
56 # Set all values inside polygon to one
59 base_array[np.invert(fill)] = 0
64 # (Row, Col) Vertices of Polygon (Defined Clockwise)
73 # print( timeit(lambda:create_polygon([20,20], vertices), number=100000) )
74 polygon_array = create_polygon((14,19), vertices)
76 print(polygon_array.astype(np.int32))
78 # This section prints numbers at each vertex for visual check, just comment out
79 # to print an array of only zeros and ones
80 # for n, vertex in enumerate(vertices):
81 # polygon_array[vertex[0],vertex[1]] = 10*(n+1)
83 # Simple routine to print the final array
84 # for row in polygon_array.tolist():
86 # print( '{:4.1f}'.format(c) )
89 # print(polygon_array.astype(np.int32))