def _expand_dim_specification(image_shape, dim_spec):
    """Expand mex dimension specification.

    The dimension specification can be 2 or 3 long, it is
    processed in two steps:
    1. If it is of length 2, a -1 is prepended to it
    2. Each dimension with -1 is replaced with the whole corresponding image dimension

    Args:
        image_shape : list(int)
            the shape of the input image, of length 3 (without batch) or 4 (with bach)
        dim_spec : list(int)
            the specification to be expanded

    Returns:
        The expanded dimension specification
    """
    if len(dim_spec) != 2 and len(dim_spec) != 3:
        raise ValueError('Bad dimensions specifications, should be a list of two or three, got %s' % dim_spec)
    if len(image_shape) == 3:  # we make sure image dimensions of length 4 (includes batch)
        image_shape = [None] + image_shape
    if len(dim_spec) == 2:
        dim_spec = [-1] + list(dim_spec)
    dim_spec = dim_spec[:]  # copy, not to step on outer scope values
    for i in range(3):
        if dim_spec[i] == -1:
            dim_spec[i] = image_shape[i + 1]  # +1 for batch dimension
    return dim_spec