Torchvision's transforms function seems to rotate image

I’m loading images into a dataset class. However, when using torchvision’s transforms functions, it seems to be rotating the images 90 degrees counterclockwise. Is there a reason for this, and a way to prevent it?

transform = transforms.Compose([transforms.Resize([256, 256]),
									transforms.RandomCrop(224),
									transforms.ToTensor()])

	train_dataset = Images(data_path, transform, 'train')
class Images(data.Dataset): 
	def __init__(self, data_path, transform, mode):
		self.examples, self.labels = make_dataset(data_path, mode) 
		self.transform = transform

	def __getitem__(self, idx):

		example = self.examples[idx]
		this_img = Image.open(example)
		this_img.load()

                if self.transform:
			this_img = self.transform(this_img)

When I debug and print this_img at this point, it appears rotated. How can I prevent this? Thanks!

Hi,

There is no rotating in your code and transforms will not do that. I think the way you visualize your image has some problems. Here is the way I plot images:

x = Image.open('cat.jpg')
x.load()
transform = transforms.Compose([transforms.Resize([256, 256]),
									transforms.RandomCrop(224),
									transforms.ToTensor()])
new_x = transform(x)
plt.imshow(new_x.permute((1, 2, 0)))  # permute channels to get numpy style image

Bests

1 Like

You’re right. I was using:

plt.imsave('x.png', this_img.transpose(0,2).numpy())

to save the image, and I can see now that transposing resulted in the wrong order of dimensions. Thanks so much!