如何从Python中的二维点云在正方形网格上创建二进制掩码?

2024-07-05 14:24:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个二维点云的X和Y坐标,我想把它映射到一个二维均匀网格上,分辨率为imageResolution,初始为全零。我希望网格中覆盖2D点云的所有像素都包含一个,以生成二值图像

请注意,在我的2D点云和统一网格中都有大量的点,因此循环在这里不是有效的解决方案

我看过凸包,但我的点不一定在凸集内

我尝试了以下代码,但它没有给我正确的二进制映射,因为它只将1s分配给距离点云中的点最近的网格点(参见下图):

X = points[:,0] #1D array of X coordinates
Y = points[:,1] #1D array of Y coordinates

imageResolution = 256
xVec = np.linspace(0,800,imageResolution)
yVec = xVec

def find_index(x,y):
    xi=np.searchsorted(xVec,x)
    yi=np.searchsorted(yVec,y)
    return xi,yi

xIndex, yIndex = find_index(X,Y)

binaryMap = np.zeros((imageResolution,imageResolution))

binaryMap[xIndex,yIndex] = 1

fig = plt.figure(1)
plt.imshow(binaryMap, cmap='jet')
plt.colorbar()

请看这张图片,它显示了我的2D点云,我想要的二进制地图,以及我从上面的代码中得到的当前二进制地图。请注意,红色像素在最后一张图像中很难看到

Images describing this problem

如何从Python中的二维点云在正方形网格上创建二进制掩码

多谢各位


Tags: of代码图像网格np二进制plt像素
2条回答

未经测试的代码

基于进一步的澄清,发布第二个答案,以便更好地索引binaryMap,因为points包含浮点数

imageResoluton = 256
MAX_X = # Fill in here the max x value ever possible in `points`
MIN_X = # Fill in here the min x value ever possible in `points`
MAX_Y = # Fill in here the max y value ever possible in `points`
MIN_Y = # Fill in here the min y value ever possible in `points`

SCALE_FAC = imageResolution / max(MAX_X-MIN_X, MAX_Y-MIN_Y)

X = np.around(SCALE_FAC * points[:,0]).astype(np.int64)
Y = np.around(SCALE_FAC * points[:,1]).astype(np.int64)
X [X >= imageResolution] = imageResolution-1
Y [Y >= imageResolution] = imageResolution-1

binaryMap[X, Y] = 1

(不需要find_index()

免责声明::未经测试的建议

如果我理解正确,那么您应该标记像素的邻域,而不是用1标记单个像素

您可以尝试在binaryMap[xIndex,yIndex] = 1之前插入以下行:

DELTA_UPPER=2                                # Param. Needs fine-tuning
delta = np.arange(DELTA_UPPER).reshape(-1,1)
xIndex = xIndex + delta
xIndex [xIndex >= imageResolution] = imageResolution-1
yIndex = yIndex + delta
yIndex [yIndex >= imageResolution] = imageResolution-1

x_many, y_many = np.broadcast_arrays (xIndex[:,None], yIndex)

xIndex = x_many.reshape(-1)
yIndex = y_many.reshape(-1)

注意:

DELTA_UPPER是一个参数,您必须通过使用它进行微调。(可以从DELTA_UPPER=3开始)

相关问题 更多 >