def test(): device = torch.device("cpu") xml = "particle/nn/config/dcgan.xml" net_G = Generator(xml).to(device) # 以下为查看当前生成效果 checkpoint = torch.load( '/home/chuan/soil/output/dcgan/iterD:iterG=1:2/nLatent64/state_dict-25.tar', map_location='cpu') net_G.load_state_dict(checkpoint['generator_state_dict']) torch.manual_seed(3.14) vec = torch.randn(3000, net_G.nLatent, device=device) print(vec.shape) cubes = generate(net_G, vec) print(cubes.shape, cubes.dtype) np.save('output/geometry/gan.npy', cubes) for cube in cubes: sand = Sand(cube) # sand.visualize(voxel=True, glyph='sphere', scale_mode='scalar') # sand.visualize(vivid=False) sand.visualize(vivid=True) mlab.outline() mlab.axes() mlab.show()
def build(): num = 1000 fakeParticles = np.load( "/home/chuan/soil/output/tvsnet/vae/通道加多/no-dropout, rotation60, 1*1ConvT-no-bn/state_dict.pt")[:num] fakeParticlesTmp = [] balls = [] clumps = [] for particle in tqdm(fakeParticles): labeled = measure.label(particle, background=0) props = measure.regionprops(labeled) props.sort(key=lambda prop: prop.area) particle = props[-1].image fakeParticlesTmp.append(particle) # 外接球 sphere = Sand(particle).circumscribedSphere() balls.append([*sphere[1], sphere[0]]) # 计算clump clump = distTrans.build(particle, 0.4, 160) clump = np.hstack([clump[0], clump[1][:, np.newaxis]]) clumps.append(clump) fakeParticles = fakeParticlesTmp del fakeParticlesTmp fakeParticles = np.array([Sand(particle).toCoords() for particle in fakeParticles], dtype=object) np.save("output/clump/pipeline/fakeParticles.npy", fakeParticles) np.save("output/clump/pipeline/balls.npy", balls) np.save("output/clump/pipeline/clumps.npy", clumps) return
def testGenerate(src, model, **kwargs): particle = generateOneParticle(model, src) sand = Sand(particle) from skimage.util import random_noise sand.cube = random_noise(sand.cube, mode="gaussian", var=0.02, seed=314) print("已添加噪声!") fig = sand.visualize(**kwargs) return fig
def test(): device = torch.device("cpu") xml = "particle/nn/config/vae.xml" vae = Vae(xml).to(device) ckpt = torch.load("output/vae/nLatent64/state_dict.pt", map_location="cpu") vae.load_state_dict(ckpt) torch.manual_seed(3.14) vec = torch.randn(3000, vae.decoder.nLatent, device=device) print(vec.shape) cubes = vae.generate(vec) print(cubes.shape, cubes.dtype) np.save("output/geometry/vae.npy", cubes) for cube in cubes: sand = Sand(cube) sand.visualize(vivid=True) mlab.outline() mlab.axes() mlab.show()
def display(dataFile, savePath, thrd=0.5): data = np.load(dataFile) for i in trange(len(data)): cube = data[i] cube[cube > thrd] = 1 cube[cube <= thrd] = 0 Sand(cube).visualize(vivid=True) # mlab.outline() # mlab.axes() mlab.savefig(os.path.join(savePath, f"{i+1:04d}.png")) mlab.close() return
def testSimpleGeometry(ind, model=None): cwd = os.getcwd() os.chdir('./data/简单几何图形') filenames = sorted(os.listdir()) filename = filenames[ind] print(filename) image = skio.imread(filename, as_gray=True) image[image == 255] = 1 print(image.max()) os.chdir(cwd) x = torch.empty((3, 64, 64), dtype=torch.uint8) for i in range(3): x[i] = torch.from_numpy(image) cube = generateOneParticle(model, x) Sand(cube).visualize() mlab.outline() mlab.axes() mlab.show() mlab.savefig(filename) return
def plotParticles(saveObj=True): fakeParticles = np.load("output/clump/pipeline/fakeParticles-move.npy", allow_pickle=True) fakeParticles = np.vstack(fakeParticles) print(fakeParticles.shape) bigCubes = np.zeros(( fakeParticles[:, 0].max() - fakeParticles[:, 0].min() + 1, fakeParticles[:, 1].max() - fakeParticles[:, 1].min() + 1, fakeParticles[:, 2].max() - fakeParticles[:, 2].min() + 1 ), dtype=np.uint8) bigCubes[tuple(fakeParticles.T)] = 1 outermostLayerThickness = 4 newBigCubes = np.zeros(np.array(bigCubes.shape)+outermostLayerThickness*2) newBigCubes[outermostLayerThickness:-outermostLayerThickness, outermostLayerThickness:-outermostLayerThickness, outermostLayerThickness:-outermostLayerThickness] = bigCubes bigCubes = newBigCubes del newBigCubes print(bigCubes.shape) fig = Sand(bigCubes).visualize() if saveObj: mlab.savefig("output/clump/pipeline/fakeParticles.obj") return fig
def interpolate(z1, z2, xml="particle/nn/config/dcgan.xml"): net_G = Generator(xml) ckpt = torch.load( "output/dcgan/iterD:iterG=1:2/nLatent64/state_dict-25.tar", map_location="cpu") net_G.load_state_dict(ckpt['generator_state_dict']) betas = [0, 0.2, 0.4, 0.6, 0.8, 1] inters = [(1 - beta) * z1 + beta * z2 for beta in betas] cubes = [] for beta, z in zip(betas, inters): cubes.append(generate(net_G, z)) sand = Sand(cubes[-1]) sand.cube = sand.poseNormalization() sand.visualize(figure=f"{1-beta:.1f}-{beta:.1f}") # mlab.outline() # mlab.axes() mlab.savefig(f"/home/chuan/{1-beta:.1f}-{beta:.1f}.png") mlab.show()
def surround(z, xml="particle/nn/config/dcgan.xml", angleInd=1): net_G = Generator(xml) ckpt = torch.load( "output/dcgan/iterD:iterG=1:2/nLatent64/state_dict-25.tar", map_location="cpu") net_G.load_state_dict(ckpt['generator_state_dict']) sigmas = [0.1, 0.2, 0.3, 0.4, 0.5] noises = [torch.normal(0, sigma, size=z.size()) for sigma in sigmas] zs = [z + noise for noise in noises] cubes = [] sigmas = [0] + sigmas zs = [z] + zs for sigma, z in zip(sigmas, zs): cubes.append(generate(net_G, z)) sand = Sand(cubes[-1]) # sand.cube = sand.poseNormalization() if len(cubes) == 1: Sand(cubes[0]).visualize(figure=f"{sigma:.1f}", color=(0.9, 0.9, 0.9), opacity=1) elif len(cubes) > 1: sand.visualize(figure=f"{sigma:.1f}", color=(0, 0.6, 0.85), opacity=0.9) Sand(cubes[0]).visualize(figure=f"{sigma:.1f}", color=(1, 1, 1), opacity=1) views = mlab.view() mlab.gcf().scene.camera.zoom(0.8) if angleInd == 1: mlab.view(azimuth=views[0], elevation=views[1]) elif angleInd == 2: mlab.view(azimuth=views[0] + 120, elevation=views[1] + 60) elif angleInd == 3: mlab.view(azimuth=views[0] + 240, elevation=views[1] + 120) else: raise ValueError mlab.savefig(f"/home/chuan/{angleInd}-{sigma:.1f}.png", magnification=2)
data = np.load("data/liutao/v1/particles.npz")["testSet"] print(data.shape) for i in range(10, 11): cube = data[i, 0] lamdas = [0.1, 0.2, 0.3, 0.4, 0.5] phis = [90, 105, 130, 145, 160, 175] for lamda in lamdas: for phi in tqdm(phis): c, r = build(cube, lamda, phi) # 剔除最小的颗粒 # mask = r != r.min() # c = c[mask] # r = r[mask] # print(f"Total {len(r)} spheres.") fig = mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) mlab.points3d(*c.T, r*2, scale_factor=1, opacity=1, resolution=30, mode="sphere", color=(0.65,)*3) sand = Sand(cube) sand.visualize(vivid=True, figure=fig, color=(0, 0.6, 0.85), opacity=0.5) # mlab.title(f"Total {len(r)} spheres.") # mlab.outline() # mlab.axes() mlab.savefig(f"../myClump/{lamda}-{phi}-{len(r)}.png") mlab.close(all=True) # mlab.show()
import numpy as np from particle.pipeline import Sand from mayavi import mlab # data = np.load("output/geometry/generatedParticles/vae.npy") # initInd = 281 # for i, particle in enumerate(data[initInd:initInd+30]): # Sand(particle).visualize() # mlab.savefig(f"/home/chuan/obj/{i+1:02d}.obj") # mlab.close(all=True) data = np.load("data/liutao/v1/particles.npz")["trainSet"] print(data.shape) initInd = 114 for i, particle in enumerate(data[initInd:initInd+30]): Sand(particle[0]).visualize() mlab.savefig(f"/home/chuan/obj/{i+1:02d}.obj") mlab.savefig(f"/home/chuan/obj/{i+1:02d}.png") mlab.close(all=True)