Skip to content
Advertisement

Python – How to pass elements stored in an array into a function?

All,

I’m new to python, so hopefully this is not a dumb question, but I have not been able to find out directions/information of how to do this task.

I am trying to create a program that determines if a given pixel is within a certain region. The method I found that recommended how to test this involves calculating polygonal areas. In this case, that would involve the shoelace function, which I have already found. The polygon coordinates are stored in a 2-dimensional array as [(x,y),(x1,y1),(x2,y2)…].

The given set of test coordinates and the function representing the shoelace function are below:

import numpy as np
testCoords = [(201,203)...(275,203)]

def polyArea(x,y):
    return 0.5 * np.abs(np.dot(x, np.roll(y,1)) - np.dot(y, np.roll(x, 1)))

How do I pass the coordinates as stored in the 2-dimensional array into the shoelace function?

Advertisement

Answer

Your polyArea expects two arrays of x and y coordinates. Your testCoords variable is a list of several points represented by their (x, y) coordinates. We will turn the later into a shape that works well, by converting it to a numpy array and transposing it:

x, y = np.array(testCoords).transpose() # Often, `.transpose()` is abbreviated as `.T`

That will give you x == [201, ..., 275] and y == [203, ..., 203].

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement