2

I have a global numpy.array data which is a 200*200*3 3d-array containing 40000 points in the 3d-space.

My goal is to calculate the distance from each point to the four corners of the unit cube ((0, 0, 0),(1, 0, 0),(0, 1, 0),(0, 0, 1)),so I can determine which corner is the nearest from the it .

def dist(*point):
    return np.linalg.norm(data - np.array(rgb), axis=2)

buffer = np.stack([dist(0, 0, 0), dist(1, 0, 0), dist(0, 1, 0), dist(0, 0, 1)]).argmin(axis=0)

I wrote this piece of code and tested it, it costs me about 10ms each run . My problem is how can I improve the performance of this piece of code ,better ran in less than 1ms .

2
  • Doesn't a cube have more than 4 corners? Commented Aug 1, 2017 at 13:43
  • 1
    @JohnZwinck Only need to calculate distance to four of them. Commented Aug 1, 2017 at 13:50

1 Answer 1

3

You could use Scipy cdist -

# unit cube coordinates as array
uc = np.array([[0, 0, 0],[1, 0, 0], [0, 1, 0], [0, 0, 1]])

# buffer output
buf = cdist(data.reshape(-1,3), uc).argmin(1).reshape(data.shape[0],-1)

Runtime test

# Original approach
def org_app():
    return np.stack([dist(0, 0, 0), dist(1, 0, 0), \
       dist(0, 1, 0), dist(0, 0, 1)]).argmin(axis=0)

Timings -

In [170]: data = np.random.rand(200,200,3)

In [171]: %timeit org_app()
100 loops, best of 3: 4.24 ms per loop

In [172]: %timeit cdist(data.reshape(-1,3), uc).argmin(1).reshape(data.shape[0],-1)
1000 loops, best of 3: 1.25 ms per loop
Sign up to request clarification or add additional context in comments.

Comments

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.