首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建三维二值图像

创建三维二值图像
EN

Stack Overflow用户
提问于 2016-08-30 04:00:34
回答 2查看 1.1K关注 0票数 4

我有一个2D数组,a,包含一组100 x,y,z坐标:

代码语言:javascript
复制
[[ 0.81  0.23  0.52]
 [ 0.63  0.45  0.13]
 ...
 [ 0.51  0.41  0.65]]

我想要创建一个三维二值图像,b,在每个x,y,z维中的101个像素,坐标在0.00到1.00之间。a定义的位置上的像素值应该是1,所有其他像素的值都应该是0。

我可以用b = np.zeros((101,101,101))创建一个形状正确的零数组,但是如何分配坐标并将其切片以创建使用a的零数组

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-08-30 06:07:10

首先,从安全地将您的浮点数转到ints开始。在上下文中,请参见问题。

代码语言:javascript
复制
a_indices = np.rint(a * 100).astype(int)

接下来,将b中的索引分配给1,但是要小心使用普通的list而不是数组,否则会触发索引数组的使用。该方法的性能似乎与其他方法相当(谢谢@Divakar!:-)

代码语言:javascript
复制
b[list(a_indices.T)] = 1

我创建了一个小示例,其大小为10而不是100,二维而不是3,以举例说明:

代码语言:javascript
复制
>>> a = np.array([[0.8, 0.2], [0.6, 0.4], [0.5, 0.6]])
>>> a_indices = np.rint(a * 10).astype(int)
>>> b = np.zeros((10, 10))
>>> b[list(a_indices.T)] = 1
>>> print(b) 
[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  1.  0.  0.  0.]
 [ 0.  0.  0.  0.  1.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  1.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]
票数 4
EN

Stack Overflow用户

发布于 2016-08-30 05:58:42

你可以这样做-

代码语言:javascript
复制
# Get the XYZ indices
idx = np.round(100 * a).astype(int)

# Initialize o/p array
b = np.zeros((101,101,101))

# Assign into o/p array based on linear index equivalents from indices array
np.put(b,np.ravel_multi_index(idx.T,b.shape),1)

分配部分的运行时-

让我们使用一个更大的网格来计时。

代码语言:javascript
复制
In [82]: # Setup input and get indices array
    ...: a = np.random.randint(0,401,(100000,3))/400.0
    ...: idx = np.round(400 * a).astype(int)
    ...: 

In [83]: b = np.zeros((401,401,401))

In [84]: %timeit b[list(idx.T)] = 1 #@Praveen soln
The slowest run took 42.16 times longer than the fastest. This could mean that an intermediate result is being cached.
1 loop, best of 3: 6.28 ms per loop

In [85]: b = np.zeros((401,401,401))

In [86]: %timeit np.put(b,np.ravel_multi_index(idx.T,b.shape),1) # From this post
The slowest run took 45.34 times longer than the fastest. This could mean that an intermediate result is being cached.
1 loop, best of 3: 5.71 ms per loop

In [87]: b = np.zeros((401,401,401))

In [88]: %timeit b[idx[:,0],idx[:,1],idx[:,2]] = 1 #Subscripted indexing
The slowest run took 40.48 times longer than the fastest. This could mean that an intermediate result is being cached.
1 loop, best of 3: 6.38 ms per loop
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39218556

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档