Created
January 24, 2018 11:43
-
-
Save leon-nn/f284a26a45a92b17b6d8315d8327ceb5 to your computer and use it in GitHub Desktop.
This demonstrates how to use Mayavi/mlab to render a mesh object in a precise pixel location within a viewport of predetermined size.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
os.environ["QT_API"] = "pyqt" | |
import numpy as np | |
import matplotlib.pyplot as plt | |
from mayavi import mlab | |
if __name__ == "__main__": | |
# Create a test 100x100 RGB image: all black and a red border. This is to demonstrate how to align the viewport. | |
img = np.zeros((100, 100, 3), dtype = np.uint8) | |
img[[0, -1], :, 0] = 255 | |
img[:, [0, -1], 0] = 255 | |
# Create new Mayavi scene for rendering | |
fig = mlab.figure(size = (img.shape[1], img.shape[0])) | |
scene = fig.scene | |
# Render the original image | |
test = mlab.imshow(np.ones(img.shape[:2][::-1]), interpolate = False) | |
# Add RGB color to the rendering | |
colors = np.c_[img.reshape(-1, 3), 255 * np.ones(img.size//3, dtype = np.uint8)] | |
test.actor.input.point_data.scalars = colors | |
# Render a triangular mesh | |
x = np.array([50, 40, 60]) - 1 | |
y = np.array([20, 40, 40]) - 1 | |
z = -np.ones(x.size) | |
face = np.array([[0, 1, 2]]) | |
tmesh = mlab.triangular_mesh(x - img.shape[1]/2, y - img.shape[0]/2, z, face, scalars = np.arange(x.size)) | |
# Add texture to the triangular mesh | |
texture = 255 * np.c_[np.eye(3, dtype = np.uint8), np.ones(x.size, dtype = np.uint8)] | |
tmesh.module_manager.scalar_lut_manager.lut.table = texture | |
# Remove the default Mayavi lighting | |
tmesh.actor.property.lighting = False | |
# Remove the toolbar in the figure window | |
scene._tool_bar.setVisible(False) | |
# Change the view of the scene to look at the x-y image plane | |
mlab.view(180, 180, 'auto', 'auto') | |
# Set a parallel projection for the scene camera | |
scene.parallel_projection = True | |
scene.camera.parallel_scale = (img.shape[0] - 1)/2 | |
# Save the scene into a NumPy array | |
rendering = mlab.screenshot() | |
plt.figure() | |
plt.imshow(rendering, interpolation = 'None') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment