Python Forum
Try to Avoid for-loops for performance
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Try to Avoid for-loops for performance
#1
Hey everyone! :)

I need some help to boost my performance.

I got a given volume, which is a 3d-matrix out of 0s and 1s, representing the voxels. I also got a List of points. For every voxel in the volume, I would like to know the distance to the closest point contained in the list. The following code can be very time-consuming.

Result_Distances = np.zeros((10,10,10))
Volume = np.ones((10,10,10)) # or any other 3d matrix with 1s or 0s
ListofPoints = [(2,3,2), (2,3,3) ,(2,6,4),(9,6,8)] # or other points

for index, voxel in np.ndenumerate(Volume):

    if voxel == 1:    

            for index2 in ListofPoints:
                distance = np.sqrt((index[0]-index2[0])**2+(index[1]-index2[1])**2+(index[2]-index2[2])**2)
                distances.append(distance)

            Result_Distances[index] = np.amin(distances)
I saved the Distances for each voxel of the Volume in a matrix with the same shape, so the same Indeces point in the two matrixes to the same corresponding point or distance. So in analogy, the expected result would be the Distance_matrix which has for each Voxel(x,y,z) in the Volume on the same element in the Distance-Matrix the Distanz to the closest Point (doesn't matter which point is the closest one)


This takes about 1 Minute to compute because my volume can be very big (>1000 voxels). My ListofPoints is smaller (about 100 points).

Is there a smart way I can avoid the time consuming for loops in this particular case? I also tried the map() function, but couldn't implement it in a way, so there is an improvement.

Thank you for your help!
Reply


Messages In This Thread
Try to Avoid for-loops for performance - by Phase1997 - Apr-01-2020, 07:18 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020