"TypeError: __init__() takes 1 positional argument but 2 were given"

I am unable to find a solution to this error:

—> 92 image = T.ToTensor(image)
93 if not self.long_mask:
94 mask = T.ToTensor(mask)

TypeError: init() takes 1 positional argument but 2 were given

You have to create the transformation object first before calling it or you could use the functional API directly:

transforms.ToTensor(image) # wrong
# TypeError: __init__() takes 1 positional argument but 2 were given

# create the object first
transform = transforms.ToTensor()
out = transform(image)

# functional API
out = torchvision.transforms.functional.to_tensor(image)
   Thank you for your reply. The first solution works. But, the second one is not working. Can you explain it?

—> 92 image = F.to_tensor(image)
93 if not self.long_mask:
94 mask = F.to_tensor(mask)

AttributeError: module ‘torch.nn.functional’ has no attribute ‘to_tensor’

   70     def __call__(self, image, mask):
   71         # transforming to PIL image

—> 72 image, mask = F.to_pil_image(image), F.to_pil_image(mask)
73
74 # random crop

AttributeError: module ‘torch.nn.functional’ has no attribute ‘to_pil_image’

In my code snippet you can see the proper namespace as torchvision.transforms.functional so use this instead of torch.nn.functional.

1 Like