PIL won’t work with tensor of size (40,40,40) and nor with (40,40,40,1).
It takes tensors an treat them like image objects. The sizes acceptable are (X,Y), (X,Y,1), (X,Y,3), (X,Y,4), where the  X,Y are height and width of your image
You can read each element of your (40,40,40) shaped tensor, if you pass arr[i] to fromarray()
And you are right, this is not related to PyTorch. And it will be difficult to find an answer on PyTorch forum