Home > Net >  PIL to numpy and PIL to tensor is different
PIL to numpy and PIL to tensor is different

Time:10-29

I have image and sum torch tensor and numpy array is diffrent, why? How to torch_img.sum() = numpy_float_img.sum()?

from PIL import Image
from torchvision import transforms as T

# Read image with PIL
img = Image.open(img_path).resize((224,224))

torch_img = T.ToTensor()(img)
numpy_img = np.asarray(img)
numpy_img_float = np.asarray(img).astype(np.float32)

print(torch_img.sum(), numpy_img.sum(), numpy_img_float.sum())
->56914.496, 14513196, 14513196.0

Does anyone have any idea why?

CodePudding user response:

Notice how torch_img is in the [0,1] range while numpy_img and numpy_img_float are both in the [0, 255] range. Looking at the documentation for torchvision.transforms.ToTensor, if the provided input is a PIL image, then the values will be mapped to [0, 1]. In contrast, numpy.array will have the values remain in the [0, 255] range.

Other than that the small variations in results are caused by different floating-point precisions.

  • Related