code: def write_itk(image_np, output_file, affine, dtype, compress):
      if isinstance(image_np, torch.Tensor):
          image_np = image_np.numpy()
      if isinstance(affine, torch.Tensor):
          affine = affine.numpy()
      if len(image_np.shape) >= 2:
          image_np = image_np.transpose().copy()
      if dtype:
          image_np = image_np.astype(dtype)
  
      result_image = itk.image_from_array(image_np)
      logger.debug(f"ITK Image size: {itk.size(result_image)}")
  
      # https://github.com/RSIP-Vision/medio/blob/master/medio/metadata/affine.py#L108-L121
      if affine is not None:
          convert_aff_mat = np.diag([-1, -1, 1, 1])
          if affine.shape[0] == 3:  # Handle RGB (2D Image)
              convert_aff_mat = np.diag([-1, -1, 1])
          affine = convert_aff_mat @ affine
  
          dim = affine.shape[0] - 1
          _origin_key = (slice(-1), -1)
          _m_key = (slice(-1), slice(-1))
  
          origin = affine[_origin_key]
          spacing = np.linalg.norm(affine[_m_key] @ np.eye(dim), axis=0)
          direction = affine[_m_key] @ np.diag(1 / spacing)
  
          logger.debug(f"Affine: {affine}")
          logger.debug(f"Origin: {origin}")
          logger.debug(f"Spacing: {spacing}")
          logger.debug(f"Direction: {direction}")
  
          result_image.SetDirection(itk.matrix_from_array(direction))
          result_image.SetSpacing(spacing)
          result_image.SetOrigin(origin)
  
      itk.imwrite(result_image, output_file, compress)
  
imports: import logging
  import tempfile
  from typing import Any, Dict, Iterable, List, Optional, Tuple
  import itk
  import nrrd
  import numpy
  import torch
  from monai.data import MetaTensor
  from monai.data.image_writer import NibabelWriter
  from monailabel.utils.others.detection import create_slicer_detection_json
  from monailabel.utils.others.generic import file_ext
  from monailabel.utils.others.pathology import create_asap_annotations_xml, create_dsa_annotations_json
label_desc: Use image node_id 2 for calling a global function with example usage: write_itk(image_np, output_file, affine, dtype, compress) without return types