Ejemplo n.º 1
0
    def __init__(self, ax, transform, Z, *args, **kwargs):
        n2, n1 = Z.shape
        X, Y = np.meshgrid(np.linspace(-0.5, +0.5, n1),
                           np.linspace(-0.5, +0.5, n2))
        vertices = np.c_[X.ravel(), Y.ravel(), Z.ravel()]
        F = (np.arange((n2-1)*(n1)).reshape(n2-1,n1))[:,:-1].T
        F = np.repeat(F.ravel(),6).reshape(n2-1,n1-1,6)
        F[:,:] += 0,n1+1,1, 0,n1,n1+1
        faces = F.reshape(-1,3)

        # Recompute colors for triangles based on vertices color
        facecolors = kwargs["facecolors"].reshape(-1,4)
        facecolors =  facecolors[faces].mean(axis=-2)
        facecolors = facecolors.reshape(-1,4)[:,:3]

        F = vertices[faces]
        # Light direction
        direction = glm.normalize([1.5,1.5,-1])
        # Faces center
        C = F.mean(axis=1)
        # Faces normal
        N = glm.normalize(np.cross(F[:,2]-F[:,0], F[:,1]-F[:,0]))
        # Relative light direction
        D = glm.normalize(C - direction)
        # Diffuse term
        diffuse = glm.clip((N*D).sum(-1).reshape(-1,1))

        facecolors = (1-diffuse)*facecolors
        kwargs["facecolors"] = facecolors
        
        Mesh.__init__(self, ax, transform, vertices, faces, *args, **kwargs)
Ejemplo n.º 2
0
    V, Vi = [], []
    with open(filename) as f:
       for line in f.readlines():
           if line.startswith('#'): continue
           values = line.split()
           if not values: continue
           if values[0] == 'v':
               V.append([float(x) for x in values[1:4]])
           elif values[0] == 'f' :
               Vi.append([int(x) for x in values[1:4]])
    return np.array(V), np.array(Vi)-1



# --- main --------------------------------------------------------------------
if __name__ == "__main__":
    import matplotlib.pyplot as plt

    fig = plt.figure(figsize=(4,4))
    ax = fig.add_axes([0,0,1,1], xlim=[-1,+1], ylim=[-1,+1], aspect=1)
    ax.axis("off")

    camera = Camera("ortho", scale=2)
    vertices, faces = obj_load("data/bunny.obj")
    vertices = glm.fit_unit_cube(vertices)
    mesh = Mesh(ax, camera.transform, vertices, faces,
                cmap=plt.get_cmap("magma"),  edgecolors=(0,0,0,0.25))
    camera.connect(ax, mesh.update)
    plt.savefig("bunny.png", dpi=600)
    plt.show()
Ejemplo n.º 3
0
            indices.append(i * (slices) + j + 1)
            indices.append(i * (slices) + j + slices + 1)
            indices.append(i * (slices) + j + slices)
            c = (i + j) % 2
            colors.append([c, c, c, 1 - c * 0.1])
    indices = np.array(indices).reshape(-1, 4)
    return vertices, indices, np.array(colors).reshape(-1, 4)


# --- main --------------------------------------------------------------------
if __name__ == "__main__":
    import matplotlib.pyplot as plt

    fig = plt.figure(figsize=(4, 4))
    ax = fig.add_axes([0, 0, 1, 1], xlim=[-1, +1], ylim=[-1, +1], aspect=1)
    ax.axis("off")

    camera = Camera("perspective", 145, 35, scale=1)
    vertices, faces, facecolors = sphere(0.75)
    mesh = Mesh(ax,
                camera.transform,
                vertices,
                faces,
                facecolors=facecolors,
                edgecolors="white",
                mode="all")
    camera.connect(ax, mesh.update)

    plt.savefig("checkered-sphere.png", dpi=600)
    plt.show()
Ejemplo n.º 4
0
    white = (1.0, 1.0, 1.0, 0.8)
    black = (0.0, 0.0, 0.0, 1.0)

    fig = plt.figure(figsize=(8, 8))

    # Model loading
    vertices, faces = obj_load("data/bunny.obj")

    ax = subplot(221)
    ax.axis("off")
    camera = Camera("perspective", -20, 0, 1.5)
    mesh = Mesh(ax,
                camera.transform,
                vertices,
                faces,
                linewidths=.5,
                cmap=plt.get_cmap("magma"),
                edgecolors=(0, 0, 0, 0.25))
    camera.connect(ax, mesh.update)

    ortho = glm.ortho(-1, +1, -1, +1, 1, 100) @ glm.scale(2)

    ax = subplot(222)
    camera = ortho @ glm.xrotate(90)
    mesh = Mesh(ax,
                camera,
                vertices,
                faces,
                facecolors=white,
                edgecolors=black,
Ejemplo n.º 5
0
            indices.append(i * (slices) + j + slices + 1)

            indices.append(i * (slices) + j + slices + 1)
            indices.append(i * (slices) + j + slices)
            indices.append(i * (slices) + j)

    indices = np.array(indices)
    indices = indices.reshape(len(indices) // 3, 3)
    return vertices, indices


# --- main --------------------------------------------------------------------
if __name__ == "__main__":
    import matplotlib.pyplot as plt

    fig = plt.figure(figsize=(4, 4))
    ax = fig.add_axes([0, 0, 1, 1], xlim=[-1, +1], ylim=[-1, +1], aspect=1)
    ax.axis("off")

    camera = Camera("perspective", -35, 60)
    vertices, faces = sphere(0.75, 128, 128)
    facecolors = lighting(vertices[faces], (-1, 1, 1), (1, 0, 0), True)
    mesh = Mesh(ax,
                camera.transform,
                vertices,
                faces,
                facecolors=facecolors,
                linewidths=0)
    camera.connect(ax, mesh.update)
    plt.show()
Ejemplo n.º 6
0
# can be applied to Cohen’s D (C as done here) or
# statistical values (statscondCluster.F_obs or F_obs_plot)
# of inter-individual brain connectivity

# defining manually bad channel for viz test
epo1.info['bads'] = ['F8', 'Fp2', 'Cz', 'O2']
epo2.info['bads'] = ['F7', 'O1']

# Visualization of inter-brain connectivity in 2D
# defining head model and adding sensors
fig, ax = plt.subplots(1, 1)
ax.axis("off")
vertices, faces = viz.get_3d_heads()
camera = Camera("ortho", theta=90, phi=180, scale=1)
mesh = Mesh(ax, camera.transform @ glm.yrotate(90), vertices, faces,
            facecolors='white',  edgecolors='black', linewidths=.25)
camera.connect(ax, mesh.update)
plt.gca().set_aspect('equal', 'box')
plt.axis('off')
viz.plot_sensors_2d(epo1, epo2, lab=True)  # bads are represented as squares
# plotting links according to sign (red for positive values,
# blue for negative) and value (line thickness increases
# with the strength of connectivity)
viz.plot_links_2d(epo1, epo2, C=C, threshold=2, steps=10)
plt.tight_layout()
plt.show()

# Visualization of inter-brain connectivity in 3D
# defining head model and adding sensors
vertices, faces = viz.get_3d_heads()
fig = plt.figure()
Ejemplo n.º 7
0
    import matplotlib.pyplot as plt

    fig = plt.figure(figsize=(6, 6))
    ax = fig.add_axes([0, 0, 1, 1], xlim=[-1, +1], ylim=[-1, +1], aspect=1)
    ax.axis("off")

    vertices, faces = sphere(0.25, 64, 64)
    camera = glm.ortho(-1, +1, -1, +1, 1, 100)

    ambient_color = np.array([1, 0, 0])
    diffuse_color = np.array([1, .25, .25])
    specular_color = np.array([1, 1, 1])

    for x, d in zip(np.linspace(-0.75, 0.75, 4), [0.00, 0.25, 0.50, 0.75]):
        diffuse_strength = d
        ambient_strength = 1 - d
        for y, shininess in zip(np.linspace(0.75, -0.75, 4), [0, 16, 8, 4]):
            facecolors = lighting(vertices[faces], (1.0, 0.5, 1.5),
                                  ambient_color, ambient_strength,
                                  diffuse_color, diffuse_strength,
                                  specular_color, shininess)
            mesh = Mesh(ax,
                        camera @ glm.translate(x, y, 0.0),
                        vertices,
                        faces,
                        facecolors=facecolors,
                        linewidths=0)

    plt.savefig("spheres.png", dpi=600)
    plt.show()
Ejemplo n.º 8
0
    vertices, faces = nb.freesurfer.io.read_geometry('data/lh.pial')
    vertices = glm.fit_unit_cube(vertices)
    facecolors = lighting(vertices[faces],
                          direction=(-1, 0, 0.25),
                          color=(1.0, 0.5, 0.5),
                          specular=True)

    camera = glm.ortho(-1, +1, -1, +1, 1, 100)
    camera = camera @ glm.scale(1.9) @ glm.yrotate(90) @ glm.xrotate(270)

    start = time.time()
    Mesh(ax,
         camera,
         vertices,
         faces,
         facecolors=facecolors,
         linewidths=0,
         mode="front")
    elapsed = time.time() - start

    text = "{0} vertices, {1} faces rendered in {2:.2f} second(s) with matplotlib"
    text = text.format(len(vertices), len(faces), elapsed)
    ax.text(0,
            0,
            text,
            va="bottom",
            ha="left",
            transform=ax.transAxes,
            size="x-small")
    plt.savefig("cortex.png", dpi=600)
Ejemplo n.º 9
0
    def __init__(self, ax, transform, Z, border=True, *args, **kwargs):

        if border:
            n2, n1 = Z.shape
            Z_ = np.zeros((n2 + 2, n1 + 2))
            Z_[1:-1, 1:-1] = Z
            Z = Z_

            x = np.zeros(n1 + 2)
            x[1:-1] = np.linspace(-0.5, +0.5, n1)
            x[0], x[-1] = x[1], x[-2]

            y = np.zeros(n2 + 2)
            y[1:-1] = np.linspace(-0.5, +0.5, n2)
            y[0], y[-1] = y[1], y[-2]

            F = kwargs["facecolors"]
            F_ = np.zeros((F.shape[0] + 2, F.shape[1] + 2, F.shape[2]))
            F_[1:-1, 1:-1] = F
            F_[0, :] = F_[1, :]
            F_[-1, :] = F_[-2, :]
            F_[:, 0] = F_[:, 1]
            F_[:, -1] = F_[:, -2]
            kwargs["facecolors"] = F_

        else:
            n2, n1 = Z.shape
            x = np.linspace(-0.5, +0.5, n1)
            y = np.linspace(-0.5, +0.5, n2)

        n2, n1 = Z.shape
        X, Y = np.meshgrid(x, y)

        vertices = np.c_[X.ravel(), Y.ravel(), Z.ravel()]
        F = (np.arange((n2 - 1) * (n1)).reshape(n2 - 1, n1))[:, :-1].T
        F = np.repeat(F.ravel(), 6).reshape(n2 - 1, n1 - 1, 6)
        F[:, :] += 0, n1 + 1, 1, 0, n1, n1 + 1

        faces = F.reshape(-1, 3)

        # Recompute colors for triangles based on vertices color
        facecolors = kwargs["facecolors"].reshape(-1, 4)
        facecolors = facecolors[faces].mean(axis=-2)
        facecolors = facecolors.reshape(-1, 4)[:, :3]

        F = facecolors.reshape(n1 - 1, n2 - 1, 2, 3)
        F[0] = F[-1] = F[:, 0] = F[:, -1] = .75, .75, .75

        F = vertices[faces]
        # Light direction
        direction = glm.normalize([1.5, 1.5, -1])
        # Faces center
        C = F.mean(axis=1)
        # Faces normal
        N = glm.normalize(np.cross(F[:, 2] - F[:, 0], F[:, 1] - F[:, 0]))
        # Relative light direction
        D = glm.normalize(C - direction)
        # Diffuse term
        diffuse = glm.clip((N * D).sum(-1).reshape(-1, 1))

        facecolors = (1 - diffuse) * facecolors

        kwargs["facecolors"] = facecolors

        Mesh.__init__(self, ax, transform, vertices, faces, *args, **kwargs)
Ejemplo n.º 10
0
    V = V.ravel()
    V = (V - V.min()) / (V.max() - V.min())

    cmap = plt.get_cmap("magma")
    norm = mpl.colors.Normalize(vmin=0, vmax=1)
    facecolors = cmap(norm(V))
    facecolors[:, 3] = 0.5 * V * V
    sizes = 25 + 50 * V

    fig = plt.figure(figsize=(6, 6))
    ax = fig.add_axes([0, 0, 1, 1], xlim=[-1, +1], ylim=[-1, +1], aspect=1)
    ax.axis("off")

    camera = Camera("perspective", 45, 35)
    scatter = Scatter(ax, camera.transform, vertices, sizes, facecolors)
    cube = Mesh(ax,
                camera.transform,
                np.array(cube["vertices"]) / 2,
                np.array(cube["faces"]),
                facecolors="None",
                edgecolors=(0, 0, 0, .5),
                mode="front")

    def update(transform):
        scatter.update(transform)
        cube.update(transform)

    camera.connect(ax, update)
    plt.savefig("volume.png", dpi=300)
    plt.show()