original_docstring: 
      Copy metadata, UID and structural information from one image to another
      Works also for different dimensions, returns new_image with copied structural info
      :param new_image: sitk.Image
      :param reference_sitk_img: sitk.Image
      :param path: full file path as str
      :return:
      
docstring: Copy metadata, UID and structural information from one image to another
  Works also for different dimensions, returns new_image with copied structural info
docstring_tokens: Copy metadata UID and structural information from one image to another Works also for different dimensions returns new_image with copied structural info
code: def copy_meta_and_save(new_image, reference_sitk_img, full_filename=None, override_spacing=None, copy_direction=True):
      """
      Copy metadata, UID and structural information from one image to another
      Works also for different dimensions, returns new_image with copied structural info
      :param new_image: sitk.Image
      :param reference_sitk_img: sitk.Image
      :param path: full file path as str
      :return:
      """
  
      t1 = time()
      try:
          # make sure this method works with nda and sitk images
          if isinstance(new_image, np.ndarray):
              if len(new_image.shape) == 4:
                  # 4D needs to be built from a series
                  new_image = [sitk.GetImageFromArray(img) for img in new_image]
                  new_image = sitk.JoinSeries(new_image)
              else:
                  new_image = sitk.GetImageFromArray(new_image)
          if full_filename:
              ensure_dir(os.path.dirname(os.path.abspath(full_filename)))
  
          if reference_sitk_img is not None:
              assert (isinstance(reference_sitk_img, sitk.Image)), 'no reference image given'
              assert (isinstance(new_image, sitk.Image)), 'only np.ndarrays and sitk images could be stored'
  
              # copy metadata
              for key in reference_sitk_img.GetMetaDataKeys():
                  new_image.SetMetaData(key, get_metadata_maybe(reference_sitk_img, key))
              # logging.debug('Metadata_copied: {:0.3f}s'.format(time() - t1))
  
              # copy structural informations to image with same dimension and size
              if (reference_sitk_img.GetDimension() == new_image.GetDimension()) and (
                      reference_sitk_img.GetSize() == new_image.GetSize()):
                  new_image.CopyInformation(reference_sitk_img)
  
              # same dimension (e.g. 4) but different size per dimension
              elif (reference_sitk_img.GetDimension() == new_image.GetDimension()):
  
                  # copy spacing, origin and rotation but keep size as it is
                  if copy_direction:
                      new_image.SetDirection(reference_sitk_img.GetDirection())
                  new_image.SetOrigin(reference_sitk_img.GetOrigin())
                  new_image.SetSpacing(reference_sitk_img.GetSpacing())
  
              # copy structural information to smaller images e.g. 4D to 3D
              elif reference_sitk_img.GetDimension() > new_image.GetDimension():
                  shape_ = len(new_image.GetSize())
                  reference_shape = len(reference_sitk_img.GetSize())
  
                  # copy direction to smaller images
                  # 1. extract the direction, 2. create a matrix, 3. slice by the new shape, 4. flatten
                  if copy_direction:
                      direction = np.array(reference_sitk_img.GetDirection())
                      dir_ = direction.reshape(reference_shape, reference_shape)
                      direction = dir_[:shape_, :shape_].flatten()
                      new_image.SetDirection(direction)
  
                  new_image.SetOrigin(reference_sitk_img.GetOrigin()[:shape_])
                  new_image.SetSpacing(reference_sitk_img.GetSpacing()[:shape_])
  
              # copy structural information to bigger images e.g. 3D to 4D, fill with 1.0 spacing
              else:
                  ones = [1.0] * (new_image.GetDimension() - reference_sitk_img.GetDimension())
                  new_image.SetOrigin((*reference_sitk_img.GetOrigin(), *ones))
                  new_image.SetSpacing((*reference_sitk_img.GetSpacing(), *ones))
                  # we cant copy the direction from smaller images to bigger ones
  
              # logging.debug('spatial data_copied: {:0.3f}s'.format(time() - t1))
  
              if override_spacing:
                  new_image.SetSpacing(override_spacing)
  
          if full_filename:
  
              # copy uid
              writer = sitk.ImageFileWriter()
              # writer.KeepOriginalImageUIDOn()
              writer.SetFileName(full_filename)
              writer.Execute(new_image)
              logging.debug('image saved: {:0.3f}s'.format(time() - t1))
              return True
          else:
              return new_image
      except Exception as e:
          logging.error('Error with saving file: {} - {}'.format(full_filename, str(e)))
          return False
code_tokens: def copy_meta_and_save ( new_image , reference_sitk_img , full_filename = None , override_spacing = None , copy_direction = True ) : t1 = time ( ) try : if isinstance ( new_image , np . ndarray ) : if len ( new_image . shape ) == 4 : new_image = [ sitk . GetImageFromArray ( img ) for img in new_image ] new_image = sitk . JoinSeries ( new_image ) else : new_image = sitk . GetImageFromArray ( new_image ) if full_filename : ensure_dir ( os . path . dirname ( os . path . abspath ( full_filename ) ) ) if reference_sitk_img is not None : assert ( isinstance ( reference_sitk_img , sitk . Image ) ) , 'no reference image given' assert ( isinstance ( new_image , sitk . Image ) ) , 'only np.ndarrays and sitk images could be stored' for key in reference_sitk_img . GetMetaDataKeys ( ) : new_image . SetMetaData ( key , get_metadata_maybe ( reference_sitk_img , key ) ) if ( reference_sitk_img . GetDimension ( ) == new_image . GetDimension ( ) ) and ( reference_sitk_img . GetSize ( ) == new_image . GetSize ( ) ) : new_image . CopyInformation ( reference_sitk_img ) elif ( reference_sitk_img . GetDimension ( ) == new_image . GetDimension ( ) ) : if copy_direction : new_image . SetDirection ( reference_sitk_img . GetDirection ( ) ) new_image . SetOrigin ( reference_sitk_img . GetOrigin ( ) ) new_image . SetSpacing ( reference_sitk_img . GetSpacing ( ) ) elif reference_sitk_img . GetDimension ( ) > new_image . GetDimension ( ) : shape_ = len ( new_image . GetSize ( ) ) reference_shape = len ( reference_sitk_img . GetSize ( ) ) if copy_direction : direction = np . array ( reference_sitk_img . GetDirection ( ) ) dir_ = direction . reshape ( reference_shape , reference_shape ) direction = dir_ [ : shape_ , : shape_ ] . flatten ( ) new_image . SetDirection ( direction ) new_image . SetOrigin ( reference_sitk_img . GetOrigin ( ) [ : shape_ ] ) new_image . SetSpacing ( reference_sitk_img . GetSpacing ( ) [ : shape_ ] ) else : ones = [ 1.0 ] * ( new_image . GetDimension ( ) - reference_sitk_img . GetDimension ( ) ) new_image . SetOrigin ( ( * reference_sitk_img . GetOrigin ( ) , * ones ) ) new_image . SetSpacing ( ( * reference_sitk_img . GetSpacing ( ) , * ones ) ) if override_spacing : new_image . SetSpacing ( override_spacing ) if full_filename : writer = sitk . ImageFileWriter ( ) writer . SetFileName ( full_filename ) writer . Execute ( new_image ) logging . debug ( 'image saved: {:0.3f}s' . format ( time ( ) - t1 ) ) return True else : return new_image except Exception as e : logging . error ( 'Error with saving file: {} - {}' . format ( full_filename , str ( e ) ) ) return False
short_docstring: Copy metadata, UID and structural information from one image to another
  Works also for different dimensions, returns new_image with copied structural info
short_docstring_tokens: Copy metadata UID and structural information from one image to another Works also for different dimensions returns new_image with copied structural info
comment: """
      Copy metadata, UID and structural information from one image to another
      Works also for different dimensions, returns new_image with copied structural info
      :param new_image: sitk.Image
      :param reference_sitk_img: sitk.Image
      :param path: full file path as str
      :return:
      """$SEP$# make sure this method works with nda and sitk images$SEP$# 4D needs to be built from a series$SEP$# copy metadata$SEP$# logging.debug('Metadata_copied: {:0.3f}s'.format(time() - t1))$SEP$# copy structural informations to image with same dimension and size$SEP$# same dimension (e.g. 4) but different size per dimension$SEP$# copy spacing, origin and rotation but keep size as it is$SEP$# copy structural information to smaller images e.g. 4D to 3D$SEP$# copy direction to smaller images$SEP$# 1. extract the direction, 2. create a matrix, 3. slice by the new shape, 4. flatten$SEP$# copy structural information to bigger images e.g. 3D to 4D, fill with 1.0 spacing$SEP$# we cant copy the direction from smaller images to bigger ones$SEP$# logging.debug('spatial data_copied: {:0.3f}s'.format(time() - t1))$SEP$# copy uid$SEP$# writer.KeepOriginalImageUIDOn()