Sibi
Sibi

Reputation: 2421

Lua/Torch reshape table

I have loaded a 200x200 rgb image and have passed it through a neural network by reshaping it into a 1x(200x200x3) vector using

img1=torch.reshape(img,1,image_size*image_size*3)

The output I am getting is also a 1x(200x200x3) vector. How can I reshape it into an rgb image of size 200x200 so that I can print it?

Upvotes: 0

Views: 818

Answers (1)

Manuel Lagunas
Manuel Lagunas

Reputation: 2751

You can try to use the function permute(x, y, z) to change the image to the shape 3x200x200, then you should be able to print it using itorch.image(your_image).The letters x, y, z are the index of the columns in your Tensor. Here you have an example.

x = torch.Tensor(3,4,2,5)
> x:size()
 3
 4
 2
 5
[torch.LongStorage of size 4]

y = x:permute(2,3,1,4) -- equivalent to y = x:transpose(1,3):transpose(1,2)
> y:size()
 4
 2
 3
 5
[torch.LongStorage of size 4]

After this step just do the same as you did. Let's say our img_size is 5.

th> t = torch.Tensor(5,5,3)


[0.0001s]   
th> t = t:permute(3,1,2)
                                                                          [0.0001s] 
th> t:size()
 3
 5
 5
[torch.LongStorage of size 3]
                                                                      [0.0001s] 
th> t[{2}]:fill(2)
 2  2  2  2  2
 2  2  2  2  2
 2  2  2  2  2
 2  2  2  2  2
 2  2  2  2  2
[torch.DoubleTensor of size 5x5]

                                                                      [0.0003s] 
th> t[{3}]:fill(3)
 3  3  3  3  3
 3  3  3  3  3
 3  3  3  3  3
 3  3  3  3  3
 3  3  3  3  3
[torch.DoubleTensor of size 5x5]

                                                                      [0.0004s] 
th> w = t:reshape(1,t:size(2)*t:size(3)*3)
                                                                      [0.0001s] 
th> w
Columns 1 to 26
 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  2

Columns 27 to 52
 2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  3  3

Columns 53 to 75
 3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3
[torch.DoubleTensor of size 1x75]

th> x = w:reshape(3,5,5)
                                                                      [0.0001s] 
th> x
(1,.,.) = 
  0  0  0  0  0
  0  0  0  0  0
  0  0  0  0  0
  0  0  0  0  0
  0  0  0  0  0

(2,.,.) = 
  2  2  2  2  2
  2  2  2  2  2
  2  2  2  2  2
  2  2  2  2  2
  2  2  2  2  2

(3,.,.) = 
  3  3  3  3  3
  3  3  3  3  3
  3  3  3  3  3
  3  3  3  3  3
  3  3  3  3  3
[torch.DoubleTensor of size 3x5x5]

Upvotes: 0

Related Questions