Home > Net >  More efficient method to convert XYZ coords into Spherical Coords
More efficient method to convert XYZ coords into Spherical Coords

Time:02-10

I have a script in Blender for plotting data points either in plane or spherical projection. However, the current method I have for converting my X,Y,Z coordinate for each vertex to spherical format is quite slow. Maybe some of you know of a more efficient method.

Essentially I have a (#verts,3) array of XYZ coordinates. Then I apply the following function over it.

def deg2rads(deg):
    return deg*pi/180

def spherical(row):
    x,y,z = [deg2rads(i) for i in row]
    new_x = cos(y)*cos(x)
    new_y = cos(y)*sin(x)
    new_z = sin(y)
    return new_x,new_y,new_z

polar_verts = np.apply_along_axis(spherical,1,polar_verts)

I believe apply_along_axis is not vectorized like other numpy operations. So maybe someone knows a better method? Now that I'm looking at it I think I can just vector multiply my verts to convert to rads. So that might shave a couple miliseconds off.

CodePudding user response:

Not sure if that makes your code faster. Basically you apply the function not to each coordinate-vector, but individually for x, y and z (hopefully vectorized) and afterwards stack them together.

import numpy as np

def spherical(spherical_coordinates):
    phi = spherical_coordinates[:, 0] * np.pi / 180
    theta = spherical_coordinates[:, 1] * np.pi / 180
    x = np.cos(phi) * np.cos(theta)
    y = np.sin(phi) * np.cos(theta)
    z = np.sin(theta)
    return np.column_stack([x, y, z])

spherical(polar_verts)

Assuming polar_verts has shape (#verts, 3).

But @DmitriChubarov is right: You're converting from spherical to cartesian coordinates, not the other way round. I would suggest to rename the function: spherical --> spherical_to_cartesian.

  • Related