简体   繁体   中英

Display 3D image given a numpy array of size (64,64,64) where each element represents the intensity(0-1)(grayscale) in 3d space in Python

I am trying to do a 3D reconstruction project using GANs and trying to check my output #which is a 64,64,64 numpy array. However I cant find a way to display the numpy array.

Tried something like

array = np.random.rand(64, 64,64)


plt.imshow(array)
plt.show()

Output

Invalid shape (10, 10, 10) for image data

3d plots are done with '3d' projection. You have several choices, but none, I think are perfect for such example.

You could plot 3d scatter plot. Or voxels.

But in all cases, you have a very pragmatic problem: you can't see if there are things between your eye and an object

import matplotlib.pyplot as plt
import numpy as np

N=20
array = np.random.rand(N, N, N)

x=np.linspace(0,N-1,N)
y=np.linspace(0,N-1,N)
z=np.linspace(0,N-1,N)
gridx, gridy, gridz=np.meshgrid(x,y,z)
ax = plt.figure().add_subplot(projection='3d')
ax.scatter(gridx, gridy, gridz, c=array)
plt.show()

在此处输入图像描述

Note that with N=20 it is quite messy, so 64 is impossible (plus very heavy for even a good computer)

Also random voxels would hardly make any visual sense anyway.

Another options is voxels. But voxels are array of booleans, which contains False for voxels to be drawn, and true for others. You can add an optional color array

import matplotlib.pyplot as plt
import numpy as np

N=20
array = np.random.rand(N, N, N)

ax = plt.figure().add_subplot(projection='3d')
# Just an array of r,g,b,a colors. With arbitrary choices on my behalf
colors=np.zeros((N,N,N,4))
colors[:,:,:,0] = 1-array
colors[:,:,:,1] = 2-np.clip(array, 0.5, 1)*2
colors[:,:,:,3] = array
ax.voxels(array>0.25, facecolors=colors)
plt.show()

在此处输入图像描述

If I replace pure random with a more simple shape, such as

import matplotlib.pyplot as plt
import numpy as np

N=20
x=np.linspace(0,N-1,N)
y=np.linspace(0,N-1,N)
z=np.linspace(0,N-1,N)
x, y, z=np.meshgrid(x,y,z)
array=np.sqrt((x-10)**2+(y-10)**2+(z-10)**2)

ax = plt.figure().add_subplot(projection='3d')
# Colors, half red, half yellow, along x-axis
# half opaque, half semi-transparent,m along y-axis
colors=np.zeros((N,N,N,4))
colors[:,:,:,0] = 1
colors[:10,:,:,1] = 1
colors[:,:10,:,3]=1
colors[:,10:,:,3]=0.5
# Sphere
ax.voxels(array<8, facecolors=colors)
plt.show()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM