Skip to content

plane

Utilities to compute planes from points and manipulate points between 3D and 2D.

Classes:

Name Description
Plane3D

Functions:

Name Description
normal_from_points

Compute the normal of the plane defined by a set of points with PCA.

Plane3D

Methods:

Name Description
__init__

Plane defined by the equation ax + by + cz + d = 0.

from_points

Create a plane from an array of points.

project_points

Project the given 3D points onto the plane, giving 2D coordinates.

unproject_points

Transforms the given 2D points in the plane's coordinate system back into their 3D coordinates in the main coordinate system.

Source code in python/src/data_pipeline/utils/plane.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
class Plane3D:

    def __init__(
        self,
        a: np.float64,
        b: np.float64,
        c: np.float64,
        d: np.float64,
        valid: bool = True,
    ) -> None:
        """
        Plane defined by the equation ax + by + cz + d = 0.

        Parameters
        ----------
        a : np.float64
        b : np.float64
        c : np.float64
        d : np.float64
        valid : bool, optional
            Whether the plane is valid and usable. By default True.
        """
        self.a = a
        self.b = b
        self.c = c
        self.d = d
        self.is_valid = valid

        if not self.is_valid:
            return

        self.normal = np.array([a, b, c], dtype=np.float64)

        self._compute_plane_origin()
        self._compute_plane_basis()

    def _compute_plane_origin(self):
        n = np.array([self.a, self.b, self.c], dtype=float)
        denom = np.dot(n, n)
        if denom == 0:
            raise ValueError("Invalid plane coefficients")
        self.origin = -self.d / denom * n

    def _compute_plane_basis(self):
        # Compute two vectors spanning the plane
        arbitrary = np.array([1.0, 0.0, 0.0], dtype=np.float64)
        if np.allclose(arbitrary, np.abs(self.normal)):
            arbitrary = np.array([0.0, 1.0, 0.0], dtype=np.float64)
        u = np.cross(self.normal, arbitrary).astype(np.float64)
        u /= np.linalg.norm(u)
        v = np.cross(self.normal, u).astype(np.float64)

        self.u = u
        self.v = v

    @classmethod
    def from_points(cls, points: NDArray[np.float64]) -> Plane3D:
        """
        Create a plane from an array of points.

        Parameters
        ----------
        points : NDArray[np.float64]
            An array of 3D points of shape (N, 3).

        Returns
        -------
        Plane3D
            Plane that best fits through the points.
        """
        # Compute the normal
        normal, normal_valid = normal_from_points(points)
        # logging.log(logging.DEBUG, f"{normal = }")
        # logging.log(logging.DEBUG, f"{normal_valid = }")

        # Compute the plane parameters
        a, b, c, d = _plane_abcd_from_point_normal(
            point=points.mean(axis=0), normal=normal
        )
        return cls(a=a, b=b, c=c, d=d, valid=normal_valid)

    def project_points(self, points_3D: NDArray[np.float64]) -> NDArray[np.float64]:
        """
        Project the given 3D points onto the plane, giving 2D coordinates.

        Parameters
        ----------
        points_3D : NDArray[np.float64]
            An array of 3D points of shape (N, 3).

        Returns
        -------
        NDArray[np.float64]
            An array of shape (N, 2) with the projected 2D points.

        Raises
        ------
        RuntimeError
            If the plane is invalid.
        """
        if not self.is_valid:
            raise RuntimeError("Cannot use `project_points` with an invalid plane.")
        shifted_points_3D = points_3D - self.origin
        points_projected = np.column_stack(
            (shifted_points_3D @ self.u, shifted_points_3D @ self.v)
        )
        return points_projected

    def unproject_points(self, points_2D: NDArray[np.float64]) -> NDArray[np.float64]:
        """
        Transforms the given 2D points in the plane's coordinate system back into their 3D coordinates in the main coordinate system.
        The output points of this function are all on the plane.

        Warning
        -------
        This is the inverse of `project_points` ONLY IF the points are actually on the plane.

        Parameters
        ----------
        points_2D : NDArray[np.float64]
            An array of shape (N, 2) containing 2D points in the plane's coordinate
            system.

        Returns
        -------
        NDArray[np.float64]
            An array of shape (N, 3) containing the 3D coordinates of the given points
            in the main 3D coordinate system.

        Raises
        ------
        RuntimeError
            If the plane is invalid.
        """
        if not self.is_valid:
            raise RuntimeError("Cannot use `project_points` with an invalid plane.")
        points_unprojected = (
            points_2D[:, 0:1] * self.u + points_2D[:, 1:2] * self.v + self.origin
        )
        return points_unprojected

__init__(a, b, c, d, valid=True)

Plane defined by the equation ax + by + cz + d = 0.

Parameters:

Name Type Description Default
a numpy.float64
required
b numpy.float64
required
c numpy.float64
required
d numpy.float64
required
valid bool

Whether the plane is valid and usable. By default True.

True
Source code in python/src/data_pipeline/utils/plane.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def __init__(
    self,
    a: np.float64,
    b: np.float64,
    c: np.float64,
    d: np.float64,
    valid: bool = True,
) -> None:
    """
    Plane defined by the equation ax + by + cz + d = 0.

    Parameters
    ----------
    a : np.float64
    b : np.float64
    c : np.float64
    d : np.float64
    valid : bool, optional
        Whether the plane is valid and usable. By default True.
    """
    self.a = a
    self.b = b
    self.c = c
    self.d = d
    self.is_valid = valid

    if not self.is_valid:
        return

    self.normal = np.array([a, b, c], dtype=np.float64)

    self._compute_plane_origin()
    self._compute_plane_basis()

from_points(points) classmethod

Create a plane from an array of points.

Parameters:

Name Type Description Default
points numpy.typing.NDArray[numpy.float64]

An array of 3D points of shape (N, 3).

required

Returns:

Type Description
utils.plane.Plane3D

Plane that best fits through the points.

Source code in python/src/data_pipeline/utils/plane.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
@classmethod
def from_points(cls, points: NDArray[np.float64]) -> Plane3D:
    """
    Create a plane from an array of points.

    Parameters
    ----------
    points : NDArray[np.float64]
        An array of 3D points of shape (N, 3).

    Returns
    -------
    Plane3D
        Plane that best fits through the points.
    """
    # Compute the normal
    normal, normal_valid = normal_from_points(points)
    # logging.log(logging.DEBUG, f"{normal = }")
    # logging.log(logging.DEBUG, f"{normal_valid = }")

    # Compute the plane parameters
    a, b, c, d = _plane_abcd_from_point_normal(
        point=points.mean(axis=0), normal=normal
    )
    return cls(a=a, b=b, c=c, d=d, valid=normal_valid)

project_points(points_3D)

Project the given 3D points onto the plane, giving 2D coordinates.

Parameters:

Name Type Description Default
points_3D numpy.typing.NDArray[numpy.float64]

An array of 3D points of shape (N, 3).

required

Returns:

Type Description
numpy.typing.NDArray[numpy.float64]

An array of shape (N, 2) with the projected 2D points.

Raises:

Type Description
RuntimeError

If the plane is invalid.

Source code in python/src/data_pipeline/utils/plane.py
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
def project_points(self, points_3D: NDArray[np.float64]) -> NDArray[np.float64]:
    """
    Project the given 3D points onto the plane, giving 2D coordinates.

    Parameters
    ----------
    points_3D : NDArray[np.float64]
        An array of 3D points of shape (N, 3).

    Returns
    -------
    NDArray[np.float64]
        An array of shape (N, 2) with the projected 2D points.

    Raises
    ------
    RuntimeError
        If the plane is invalid.
    """
    if not self.is_valid:
        raise RuntimeError("Cannot use `project_points` with an invalid plane.")
    shifted_points_3D = points_3D - self.origin
    points_projected = np.column_stack(
        (shifted_points_3D @ self.u, shifted_points_3D @ self.v)
    )
    return points_projected

unproject_points(points_2D)

Transforms the given 2D points in the plane's coordinate system back into their 3D coordinates in the main coordinate system. The output points of this function are all on the plane.

Warning

This is the inverse of project_points ONLY IF the points are actually on the plane.

Parameters:

Name Type Description Default
points_2D numpy.typing.NDArray[numpy.float64]

An array of shape (N, 2) containing 2D points in the plane's coordinate system.

required

Returns:

Type Description
numpy.typing.NDArray[numpy.float64]

An array of shape (N, 3) containing the 3D coordinates of the given points in the main 3D coordinate system.

Raises:

Type Description
RuntimeError

If the plane is invalid.

Source code in python/src/data_pipeline/utils/plane.py
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
def unproject_points(self, points_2D: NDArray[np.float64]) -> NDArray[np.float64]:
    """
    Transforms the given 2D points in the plane's coordinate system back into their 3D coordinates in the main coordinate system.
    The output points of this function are all on the plane.

    Warning
    -------
    This is the inverse of `project_points` ONLY IF the points are actually on the plane.

    Parameters
    ----------
    points_2D : NDArray[np.float64]
        An array of shape (N, 2) containing 2D points in the plane's coordinate
        system.

    Returns
    -------
    NDArray[np.float64]
        An array of shape (N, 3) containing the 3D coordinates of the given points
        in the main 3D coordinate system.

    Raises
    ------
    RuntimeError
        If the plane is invalid.
    """
    if not self.is_valid:
        raise RuntimeError("Cannot use `project_points` with an invalid plane.")
    points_unprojected = (
        points_2D[:, 0:1] * self.u + points_2D[:, 1:2] * self.v + self.origin
    )
    return points_unprojected

normal_from_points(points)

Compute the normal of the plane defined by a set of points with PCA.

Parameters:

Name Type Description Default
points numpy.typing.NDArray[numpy.float64]

Set of 3D points (N, 3).

required

Returns:

Type Description
numpy.typing.NDArray[numpy.float64]

Normal vector (3,).

bool

Whether the normal is valid (False if the points were collinear for example).

Raises:

Type Description
RuntimeError

If the input points are not 3D.

Source code in python/src/data_pipeline/utils/plane.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def normal_from_points(
    points: NDArray[np.float64],
) -> tuple[NDArray[np.float64], bool]:
    """
    Compute the normal of the plane defined by a set of points with PCA.

    Parameters
    ----------
    points : NDArray[np.float64]
        Set of 3D points (N, 3).

    Returns
    -------
    NDArray[np.float64]
        Normal vector (3,).
    bool
        Whether the normal is valid (False if the points were collinear for example).

    Raises
    ------
    RuntimeError
        If the input points are not 3D.
    """
    if points.shape[1] != 3:
        raise RuntimeError("3D points are expected.")
    if points.shape[0] < 3:
        return np.zeros(3), False

    # Center the data
    centroid = points.mean(axis=0)
    centered = points - centroid

    # Compute the SVD of the centered coordinates.
    U, s, Vt = np.linalg.svd(centered, full_matrices=False)

    # The normal is the singular vector associated with the smallest singular value,
    normal = Vt[-1]
    normal /= np.linalg.norm(normal)

    # Check if the points seem to be in the same plane:
    planarity_ratio = (s[0] - s[2]) / s[0]
    linearity_ratio = (s[0] - s[1]) / s[0]
    # valid = planarity_ratio > 0.999 and linearity_ratio < 0.999
    valid = planarity_ratio > 0.999
    if not valid:
        logging.log(logging.DEBUG, "Invalid plane:")
        logging.log(logging.DEBUG, f"{s = }")
        logging.log(logging.DEBUG, f"{planarity_ratio = }")
        logging.log(logging.DEBUG, f"{linearity_ratio = }")
        logging.log(logging.DEBUG, f"{points = }")

    return normal, valid