面试题目:判断点是否在box内。输入N个点(Nx3)和M个boxes(Mx8),计算哪些点在哪个box里面,输出N维向量(1xN),每个数字表示每个点所在box的index,不在box内部,返回-1.
思路(来自StackOverflow) :如下图, box的8个顶点是 ABCDEFGH
,中心点是I
,需要求证的点是P
。
- 计算三个单位法向量:
DA
、DC
、DH
- 计算
P
点到中心点I
的向量IP
- 计算向量
IP
到 三个单位法向量DA
、DC
、DH
的投影距离,再乘以2 - 距离小于box的三条边则符合要求,最后结果取交集
参考代码:
"""
判断点是否在框内
"""
import numpy as np
def inside_test(points, cube3d):
"""
cube3d = numpy array of the shape (8,3) with coordinates in the clockwise order. first the bottom plane is considered then the top one.
points = array of points with shape (N, 3).
Returns the indices of the points array which are outside the cube3d
"""
b1, b2, b3, b4, t1, t2, t3, t4 = cube3d
# 计算三个单位法向量dir1、dir2、dir3
dir1 = (t1-b1)
size1 = np.linalg.norm(dir1)
dir1 = dir1 / size1
dir2 = (</