code: def as_closest_canonical(img, enforce_diag=False):
      """Return `img` with data reordered to be closest to canonical
  
      Canonical order is the ordering of the output axes.
  
      Parameters
      ----------
      img : ``spatialimage``
      enforce_diag : {False, True}, optional
         If True, before transforming image, check if the resulting image
         affine will be close to diagonal, and if not, raise an error
  
      Returns
      -------
      canonical_img : ``spatialimage``
         Version of `img` where the underlying array may have been
         reordered and / or flipped so that axes 0,1,2 are those axes in
         the input data that are, respectively, closest to the output axis
         orientation.  We modify the affine accordingly.  If `img` is
         already has the correct data ordering, we just return `img`
         unmodified.
      """
      # Get the image class to transform the data for us
      img = img.as_reoriented(io_orientation(img.affine))
  
      # however, the affine may not be diagonal
      if enforce_diag and not _aff_is_diag(img.affine):
          raise OrientationError("Transformed affine is not diagonal")
  
      return img
  
file_path: nibabel/nibabel/funcs.py
imports: import numpy
  from .loadsave import load
  from .orientations import OrientationError, io_orientation
label_desc: Use image node_id 4 for calling a global function with example usage: as_closest_canonical(img, enforce_diag) and returns: img