Skip to content

Instantly share code, notes, and snippets.

@mm--
Created September 5, 2014 00:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mm--/4a4fc7badacfad874102 to your computer and use it in GitHub Desktop.
Save mm--/4a4fc7badacfad874102 to your computer and use it in GitHub Desktop.
Take a FreeSurfer ASCII format surface and convert to Wavefront .obj, unnecessarily rendering a rainbow-colored surface using rgl ;P
#!/usr/bin/Rscript
## Josh Moller-Mara
## Take in an .asc file created with mris_convert
## (e.g. mris_convert lh.pial lh.pial.asc)
## and then convert it into a Wavefront OBJ.
## And also unnecessarily render it with rgl :-)
library(rgl)
args <- commandArgs(trailingOnly = TRUE)
## Strings to 3 column numeric matrix
splitex <- function(strings) {
do.call(rbind, lapply(strsplit(strings, split = " +"), as.numeric))[,1:3]
}
for(file in args) {
## Read in lines, filtering out comments
lines <- grep("^(#.*)?$", readLines(file), value = TRUE, invert = TRUE)
## Get the number of vertices and the number of faces
infos <- as.numeric(unlist(strsplit(lines[1], " ")))
## Skip header
splits <- split(lines, rep(c("Header", "Vertices", "Faces"), times=c(1, infos)))
## Convert vertices
verts <- splitex(splits$Vertices)
faces <- splitex(splits$Faces) + 1 #Faces have to start at 1
## Get a list of all triangles
triangles <- verts[as.vector(t(faces)),]
rgl.open()
rgl.triangles(triangles, color = rainbow(nrow(triangles)))
play3d(spin3d(axis=c(1,0,0), rpm=60/3), duration=3)
play3d(spin3d(axis=c(0,0,-1), rpm=60/3), duration=3)
## You can't have scientific notation in .obj files
options(scipen=999)
vertLines <- paste("v", verts[,1], verts[,2], verts[,3])
faceLines <- paste("f", faces[,1], faces[,2], faces[,3])
fileConn <- file(paste0(file, ".obj"))
writeLines(c(vertLines, faceLines), fileConn)
close(fileConn)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment