my3bikaht:

I wonder if redefining img_pil inside with loop is causing this issue for the PIL library.


It seems the tensor operation is what causing this issue.
I dug a bit deeper into the transform function. The issue is caused by the following line:
tensor.sub_(mean).div_(std).
I tried to imitate it manually doing the following:
Outside the loop:
MEAN = 255 * torch.tensor([0.485, 0.456, 0.406])
STD = 255 * torch.tensor([0.229, 0.224, 0.225])
meanOP = MEAN[:, None, None]
stdOP = STD[:, None, None]

In the loop:
img_pil = (img_pil - meanOP / stdOP)
The issue is reproduced with the above.
So it seems it is related to tensor operations.