[Python] Make 3D stack of multiple 2D images with color gradient

Discussão em 'Python' iniciado por Stack, Setembro 29, 2024.

  1. Stack

    Stack Membro Participativo

    I have a set of 10 2D images that I want to stack to make a 3D image. These images are generated using matplotlib so they can be either .png or .tif. In the sample code below, I have a function plot_data() that uses gen_random_data() to get a line and plot a set of 10 2D images where the gradient color is based on the viridis() cmap. I have used meshlib.mrmeshpy to stack these images to get the 3D plot but this 3D image is not color graded. Can someone please help me implement the color I have as well? If there is another package apart from meshlib.mrmeshpy that can do this, please let me know.

    This is the code I have:

    import cv2
    import meshlib.mrmeshpy as mr
    import vtk
    import matplotlib.pyplot as plt
    import numpy as np
    import os

    def gen_random_data():
    # Generate random data
    np.random.seed(42)
    x = np.random.rand(100, 100)
    y = 2 * x + 5
    # z = np.random.rand(100, 100)
    return x, y


    def plot_data(n=10):
    for i in range(n):
    # Generate random data
    x, y = gen_random_data()
    # Plot the data
    plt.scatter(x, y, c=y)
    plt.viridis()
    plt.savefig('scatter_plots/scatter_plot_{}.tif'.format(i))
    plt.show()


    def make_stack(tif_path):

    settings = mr.LoadingTiffSettings()

    # load images from specified directory
    settings.dir = tif_path

    # specifiy size of 3D image element
    settings.voxelSize = mr.Vector3f(1, 1, 5)

    #create voxel object from the series of images
    volume = mr.loadTiffDir(settings)

    #define ISO value to build surface
    iso = 100.0 #127.0

    #convert voxel object to mesh
    mesh = mr.gridToMesh(volume, iso)

    #save mesh to .stl file
    mr.saveMesh(mesh, mr.Path(tif_path + '/' + '3d_image_stack.stl'))


    def view_stack(tif_path):
    # visualize the file:
    reader = vtk.vtkSTLReader()
    reader.SetFileName(tif_path + '/' + '3d_image_stack.stl')

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(reader.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    renderer = vtk.vtkRenderer()
    renderer.AddActor(actor)
    renderer.SetBackground(1, 1, 1)

    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)
    render_window.SetSize(800, 800)

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(render_window)

    interactor.Initialize()
    interactor.Start()


    def main():
    # Plot and provide path to TIF images
    plot_data(10)
    TIF_PATH = r'scatter_plots'

    make_stack(TIF_PATH)
    view_stack(TIF_PATH)


    if __name__ == '__main__':
    main()


    This code will generate the images and make a 3D plot. I have tried playing with the iso value but it does not affect the color.

    Continue reading...

Compartilhe esta Página