Question about array index and printing

I have question about array index

        mriidx = self.mriids[idx] #img file name
        maskidx = self.maskids[idx] #mask file name
        
        mask_file = os.path.join(self.masks_dir, maskidx)
        img_file = os.path.join(self.imgs_dir, mriidx)
        
        img = Image.open(img_file).convert("RGB")
        mask = Image.open(mask_file).convert("L")
                
        mask = np.array(mask)
        img = np.array(img)
        
        print("img shape :", img.shape,'\n', "mask shape :", mask.shape)

        obj_ids = np.unique(mask)
        
        print('obj_ids :',obj_ids)
        
        obj_ids = obj_ids[1:]
        
        print('obj_ids[1:] shape :', obj_ids[1:].shape)
        print('obj_ids[1:] :', obj_ids[1:])

and here are the two types of outputs I got

img shape : (256, 256, 3) 
 mask shape : (256, 256)
obj_ids : [0]
obj_ids[1:] shape : (0,)
obj_ids[1:] : []
img shape : (256, 256, 3) 
 mask shape : (256, 256)
obj_ids : [  0 255]
obj_ids[1:] shape : (0,)
obj_ids[1:] : []

My first question is in the first output, obj_ids is [0].
then how is obj_ids[1:] not have error? isn’t it out of index range?

and my second question is in the second output.
why does obj_ids has additional space?
doesn’t it has to be [0 255] not [    0 255]?

No, as you will get an empty tensor, if the slice is invalid (same as in numpy):

x = torch.randn(10)
n = np.random.randn(10)

print(x[11:])
> tensor([])
print(n[11:])
> []

However, direct indexing will yield an error.

Numpy formats the output like this (PyTorch as well, but with a comma :wink: ).

in the second question I was talking about
obj_ids output having additional double space in front of 0.
not the way it shows its output.

in the first output
obj_ids : [0]
it doen’t have additional double space

I still think it is the desired print format to align multiple rows by the value:

print(torch.tensor([0, 255]))
> tensor([  0, 255])
print(torch.tensor([0, 1000]))
> tensor([   0, 1000])
print(torch.tensor([[0, 10000000], [1, 1]]))
> tensor([[       0, 10000000],
          [       1,        1]])
1 Like

Oh… It follows its length of largest value…
I didn’t realized that.
Thank you very much!

1 Like

then could you tell me how obj_ids[1:] in the second output is not 255?
and how is the shape not (1, )?

You are reassigning and then slicing again the object:

obj_ids = obj_ids[1:] # here it will only have a single element
        
print('obj_ids[1:] shape :', obj_ids[1:].shape)
print('obj_ids[1:] :', obj_ids[1:]) # is empty now
1 Like