Skip to content

Instantly share code, notes, and snippets.

@Ghazi-Bouabene
Created August 4, 2017 09:14
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 Ghazi-Bouabene/514ebcd038c632de94e4df1d98e696f9 to your computer and use it in GitHub Desktop.
Save Ghazi-Bouabene/514ebcd038c632de94e4df1d98e696f9 to your computer and use it in GitHub Desktop.
Custom version of Scalar mesh IO, allowing to change the index of the read array.
package local
import java.io.{File, IOException}
import scalismo.common.Scalar
import scalismo.io.ImageIO
import scalismo.mesh.ScalarMeshField
import scalismo.utils.{MeshConversion, VtkHelpers}
import vtk.{vtkPolyData, vtkPolyDataReader}
import scala.reflect.ClassTag
import scala.reflect.runtime.universe.TypeTag
import scala.util.{Failure, Success, Try}
object MyScalarMeshIO {
private def readVTKPolydata(file: File): Try[vtkPolyData] = {
val vtkReader = new vtkPolyDataReader()
vtkReader.SetFileName(file.getAbsolutePath)
vtkReader.Update()
val errCode = vtkReader.GetErrorCode()
if (errCode != 0) {
return Failure(new IOException(s"Could not read vtk mesh (received error code $errCode"))
}
val data = vtkReader.GetOutput()
vtkReader.Delete()
Success(data)
}
def vtkPolyDataToScalarMeshField[S: Scalar: TypeTag: ClassTag](pd: vtkPolyData): Try[ScalarMeshField[S]] = {
for {
mesh <- MeshConversion.vtkPolyDataToTriangleMesh(pd)
scalarData <- VtkHelpers.vtkDataArrayToScalarArray[S](pd.GetPointData().GetArray(0).GetDataType(), pd.GetPointData().GetArray(0))
} yield {
ScalarMeshField(mesh, scalarData)
}
}
def readScalarMeshField[S: Scalar: TypeTag: ClassTag](file: File): Try[ScalarMeshField[S]] = {
val requiredScalarType = ImageIO.ScalarType.fromType[S]
val filename = file.getAbsolutePath
filename match {
case f if f.endsWith(".vtk") => readVTKPolydata(file).flatMap { pd =>
val spScalarType = ImageIO.ScalarType.fromVtkId( pd.GetPointData().GetArray(0).GetDataType())
vtkPolyDataToScalarMeshField(pd)
if (requiredScalarType != spScalarType) {
Failure(new Exception(s"Invalid scalar type (expected $requiredScalarType, found $spScalarType)"))
} else {
vtkPolyDataToScalarMeshField(pd)
}
}
case _ =>
Failure(new IOException("Unknown file type received" + filename))
}
}
def readScalarMeshFieldAsShort(file: File): Try[ScalarMeshField[Short]] = {
val filename = file.getAbsolutePath
readScalarMeshField[Short](file).recoverWith{case e => readScalarMeshField[Int](file).map(_.map(_.toShort))}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment