Skip to content

Instantly share code, notes, and snippets.

@cpsievert
Last active May 23, 2016 05:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cpsievert/5fb0b5449ada698f4c8b4d974f340728 to your computer and use it in GitHub Desktop.
Save cpsievert/5fb0b5449ada698f4c8b4d974f340728 to your computer and use it in GitHub Desktop.
Mesh surfaces with plotly and the geomerty package
library(plotly)
library(geometry)
# ----------------------------------------------------------------------
# Make sure we can reproduce the examples on ?tri.surf
# ----------------------------------------------------------------------
data1.url <- "http://neuroimage.usc.edu/USCPhantom/mesh_data.bin"
meshdata <- R.matlab::readMat(url(data1.url))
brain <- meshdata$mesh.brain[, c(1, 3, 2)]
tbr <- surf.tri(brain, delaunayn(brain))
# the 3D points
plot_ly(x = brain[, 1], y = brain[, 2], z = brain[, 3], type = "scatter3d", opacity = 0.3)
# the triangulation
plot_ly(x = brain[, 1], y = brain[, 2], z = brain[, 3],
i = tbr[, 1], j = tbr[, 2], k = tbr[, 3], type = "mesh3d")
# ----------------------------------------------------------------------
# https://plot.ly/python/triangulation/#triangulation-of-the-moebius-band
# ----------------------------------------------------------------------
g <- expand.grid(
u = seq(0, 2 * pi, length.out = 100),
v = seq(-1, 1, length.out = 50)
)
tp <- with(g, 1 + 0.5 * v * cos(u / 2))
m <- matrix(
c(tp * cos(g$u), tp * sin(g$u), 0.5 * g$v * sin(g$u / 2)),
ncol = 3, dimnames = list(NULL, c("x", "y", "z"))
)
# the points in 3D space
plot_ly(x = m[, 1], y = m[, 2], z = m[, 3], type = "scatter3d",
mode = "markers", marker = list(size = 3))
# vertices of the triangulation (not correct?!?)
# see also https://gist.github.com/timelyportfolio/f71c1ca27d309eb8ec26422fb5fe8bbb
d <- delaunayn(m)
st <- surf.tri(m, d)
vertices <- m[st, ]
plot_ly(x = vertices[, 1], y = vertices[, 2], z = vertices[, 3],
type = "scatter3d", mode = "markers", marker = list(size = 2))
# ----------------------------------------------------------------------
# https://plot.ly/python/triangulation/#plotting-trisurfaces-from-data-stored-in--plyfiles
# ----------------------------------------------------------------------
library(geomorph)
plyFile <- 'http://people.sc.fsu.edu/~jburkardt/data/ply/chopper.ply'
dest <- basename(plyFile)
if (!file.exists(dest)) {
download.file(plyFile, dest)
}
mesh <- read.ply(dest)
# see getS3method("shade3d", "mesh3d") for details on how to plot
# plot point cloud
x <- with(mesh, vb[1, it] / vb[4, it])
y <- with(mesh, vb[2, it] / vb[4, it])
z <- with(mesh, vb[3, it] / vb[4, it])
plot_ly(x = x, y = y, z = z, type = "scatter3d",
mode = "markers", marker = list(size = 3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment