kaolin.io.obj

API

Functions

kaolin.io.obj.import_mesh(path, with_materials=False, with_normals=False, error_handler=None, heterogeneous_mesh_handler=None, triangulate=False)

Load data from an obj file as a single mesh, and return data as CPU pytorch tensors in an easy-to-manage kaolin.rep.SurfaceMesh container.

Note

Currently has limited materials support for Kd, Ka, Ks, map_Kd, map_Ka and map_Ks, following the format described in: http://paulbourke.net/dataformats/obj/

Parameters
  • path (str) – path to the obj file (with extension).

  • with_materials (bool) – if True, load materials. Default: False.

  • with_normals (bool) – if True, load normals. Default: False.

  • error_handler (Callable, optional) – function that handles errors that can be raised (see raised errors, except NonHomogeneousMeshError handled separately), with the signature error_handler(error: Exception, **kwargs). Handler can provide special treatment of MaterialNotFoundError, returning a dummy material dictionary instead (if this is not the case, assignments to non-existent materials will be lost). For options see: create_missing_materials_error_handler(), skip_error_handler(), ignore_error_handler(), and default_error_handler() (Default is to raise all errors).

  • heterogeneous_mesh_handler (Callable, optional) – function that handles a heterogeneous mesh, homogenizing, returning None or throwing error, with the following signature: heterogeneous_mesh_handler(vertices, face_vertex_counts, *args, face_assignments) for example, see mesh_handler_naive_triangulate and heterogeneous_mesh_handler_skip. Default: will raise a NonHomogeneousMeshError.

  • triangulate – if True, will triangulate all non-triangular meshes using same logic as mesh_handler_naive_triangulate. If heterogeneous_mesh_handler is not set, this flag will cause non-homogeneous meshes to be triangulated and loaded without error; otherwise triangulation executes after heterogeneous_mesh_handler, which may skip or throw an error.

Returns

an unbatched instance of kaolin.rep.SurfaceMesh, where:

  • normals and face_normals_idx will only be filled if with_normals=True

  • materials will be a list of materials (see return values of load_mtl()) sorted by their material_name; filled only if with_materials=True.

  • material_assignments will be a tensor of shape (num_faces,) containing the index of the material (in the materials list) assigned to the corresponding face, or -1 if no material was assigned; filled only if with_materials=True.

Return type

(SurfaceMesh)

Raises
  • MaterialNotFoundError – The .obj is using a material not parsed from material libraries (set error_handler to skip).

  • MaterialFileError – From load_mtl(): Failed to open material path (set error_handler to skip).

  • MaterialLoadError – From load_mtl(): Failed to load material, very often due to path to map_Kd/map_Ka/map_ks being invalid (set error_handler to skip).

  • NonHomogeneousMeshError – The number of vertices were not equal for all faces (set heterogeneous_mesh_handler to handle).

Examples

To load a mesh without loading normals, materials or UVs:

>>> from kaolin.io.obj import import_mesh
>>> mesh = import_mesh("sample_data/meshes/pizza.obj")
>>> print(mesh)
SurfaceMesh object with batching strategy NONE
            vertices: [482, 3] (torch.float32)[cpu]
               faces: [960, 3] (torch.int64)[cpu]
       face_vertices: if possible, computed on access from: (faces, vertices)
        face_normals: if possible, computed on access from: (normals, face_normals_idx) or (vertices, faces)
      vertex_normals: if possible, computed on access from: (faces, face_normals)
            face_uvs: if possible, computed on access from: (uvs, face_uvs_idx)


>>> mesh.face_normals  # Causes face_normals and any attributes required to compute it to be auto-computed
>>> mesh.to_batched()  # Apply fixed topology batching, unsqueezing most attributes
>>> mesh = mesh.cuda(attributes=["vertices"])  # Moves just vertices to GPU
>>> print(mesh)
SurfaceMesh object with batching strategy FIXED
            vertices: [1, 482, 3] (torch.float32)[cuda:0]
       face_vertices: [1, 960, 3, 3] (torch.float32)[cpu]
        face_normals: [1, 960, 3, 3] (torch.float32)[cpu]
               faces: [960, 3] (torch.int64)[cpu]
      vertex_normals: if possible, computed on access from: (faces, face_normals)
            face_uvs: if possible, computed on access from: (uvs, face_uvs_idx)

To load a mesh with normals, materials and UVs, while triangulating and homogenizing if needed:

>>> from kaolin.io.obj import import_mesh
>>> from kaolin.io.utils import mesh_handler_naive_triangulate
>>> mesh = import_mesh("sample_data/meshes/pizza.obj",
                      with_normals=True, with_materials=True,
                      heterogeneous_mesh_handler=mesh_handler_naive_triangulate,
                      triangulate=True)
>>> print(mesh)
SurfaceMesh object with batching strategy NONE
            vertices: [482, 3] (torch.float32)[cpu]
             normals: [482, 3] (torch.float32)[cpu]
                 uvs: [514, 2] (torch.float32)[cpu]
               faces: [960, 3] (torch.int64)[cpu]
    face_normals_idx: [960, 3] (torch.int64)[cpu]
        face_uvs_idx: [960, 3] (torch.int64)[cpu]
material_assignments: [960] (torch.int16)[cpu]
           materials: list of length 2
       face_vertices: if possible, computed on access from: (faces, vertices)
        face_normals: if possible, computed on access from: (normals, face_normals_idx) or (vertices, faces)
      vertex_normals: if possible, computed on access from: (faces, face_normals)
            face_uvs: if possible, computed on access from: (uvs, face_uvs_idx)
kaolin.io.obj.load_mtl(mtl_path, error_handler)

Load and parse a Material file.

Followed format described in: https://people.sc.fsu.edu/~jburkardt/data/mtl/mtl.html. Currently only support diffuse, ambient and specular parameters (Kd, Ka, Ks) through single RGB values or texture maps.

Parameters

mtl_path (str) – Path to the mtl file.

Returns

Dictionary of materials, which are dictionary of properties with optional torch.Tensor values:

  • Kd: diffuse color of shape (3)

  • map_Kd: diffuse texture map of shape (H, W, 3)

  • Ks: specular color of shape (3)

  • map_Ks: specular texture map of shape (H’, W’, 3)

  • Ka: ambient color of shape (3)

  • map_Ka: ambient texture map of shape (H’’, W’’, 3)

  • material_name: string name of the material

Return type

(dict)

Raises

Error Handler

kaolin.io.obj.ignore_error_handler(error, **kwargs)

Simple error handler to use in load_obj() that ignore all errors

kaolin.io.obj.skip_error_handler(error, **kwargs)

Simple error handler to use in load_obj() that skips all errors and logs them as warnings.

kaolin.io.obj.default_error_handler(error, **kwargs)

Simple error handle to use in load_obj() that raises all errors.

kaolin.io.obj.create_missing_materials_error_handler(error, **kwargs)

Error error_handler to be provided to obj.read_mesh that can handle MaterialNotFound error, returning a dummy material with a random diffuse color instead. Material will contain an additional “error” field. MaterialFileError and MaterialLoadError will print a warning and be ignored.