In this lesson we want to learn How to Display 3D images in Python.
There are several ways to display 3D images in Python, but the popular library for doing so is mayavi. mayavi is 3D visualization library for Python that provides a simple and intuitive way to visualize 3D data.
This is how to display a 3D image using mayavi:
- Install mayavi library using pip:
1 |
pip install mayavi |
- Import mlab module from mayavi library in your Python script:
1 |
from mayavi import mlab |
- Generate 3D data to display. for example, you can create sphere:
1 2 3 |
x, y, z = np.ogrid[-5:5:64j, -5:5:64j, -5:5:64j] scalars = x * x + y * y + z * z - 100 obj = mlab.contour3d(scalars, contours=8, transparent=True) |
- Display the 3D image using the mlab.show function:
1 |
mlab.show() |
This will open window displaying 3D image of sphere. you can interact with image using your mouse and keyboard to change the camera position, zoom and rotation.
mayavi provides number of other visualization functions, such as sufr,mesh and scatter3d that allows you to display different 3D data in different ways. you can use these functions to create complex visualizations of your data and explore it in 3D.
This is the complete code for displaying a 3D image of sphere using mayavi in Python:
1 2 3 4 5 6 7 |
import numpy as np from mayavi import mlab x, y, z = np.ogrid[-5:5:64j, -5:5:64j, -5:5:64j] scalars = x * x + y * y + z * z - 100 obj = mlab.contour3d(scalars, contours=8, transparent=True) mlab.show() |
This code imports numpy library and mlab module from the mayavi library. it then generates 3D data for sphere using numpy and displays it using mlab.contour3d. the mlab.show function is called to display the 3D image in window that you can interact with using your mouse and keyboard.
This code is basic example to get you started with mayavi and display 3D image. you can explore mayavi documentation for more information on how to customize your 3D visualizations and display different types of data.