code: def _get_grouped_dicoms(dicom_input):
      
  
      # Order all dicom files by InstanceNumber
      dicoms = sorted(dicom_input, key=lambda x: x.InstanceNumber)
  
      # now group per stack
      grouped_dicoms = [[]]  # list with first element a list
      stack_index = 0
  
      # loop over all sorted dicoms and sort them by stack
      # for this we use the position and direction of the slices so we can detect a new stack easily
      previous_position = None
      previous_direction = None
      for dicom_ in dicoms:
          current_direction = None
          # if the stack number decreases we moved to the next stack
          if previous_position is not None:
              current_direction = numpy.array(dicom_.ImagePositionPatient) - previous_position
              current_direction = current_direction / numpy.linalg.norm(current_direction)
          if current_direction is not None and \
                  previous_direction is not None and \
                  not numpy.allclose(current_direction, previous_direction, rtol=0.05, atol=0.05):
              previous_position = numpy.array(dicom_.ImagePositionPatient)
              previous_direction = None
              stack_index += 1
          else:
              previous_position = numpy.array(dicom_.ImagePositionPatient)
              previous_direction = current_direction
  
          if stack_index >= len(grouped_dicoms):
              grouped_dicoms.append([])
          grouped_dicoms[stack_index].append(dicom_)
  
      return grouped_dicoms
docs: Search all dicoms in the dicom directory, sort and validate them
  
      fast_read = True will only read the headers not the data