Search code examples
cimagetorch

How to add image channel with torch?


I have loaded a jpg image with 3 channels, how to add one last channel to generate an image tensor with 4 channels?


Solution

  • Let's say you have an image with 3 channels, height height and width width:

    a = torch.Tensor(3, height, width) -- this is your image
    b = torch.Tensor(1, height, width) -- the channel you want to add
    c = torch.cat(a,b,1)
    

    A working example:

    th> a = torch.Tensor(3,3,3):fill(1)                                                               
    th> b = torch.Tensor(1,3,3):fill(0)
    th> c = torch.cat(a,b,1)                                                                   
    th> c
    (1,.,.) = 
      1  1  1
      1  1  1
      1  1  1
    
    (2,.,.) = 
      1  1  1
      1  1  1
      1  1  1
    
    (3,.,.) = 
      1  1  1
      1  1  1
      1  1  1
    
    (4,.,.) = 
      0  0  0
      0  0  0
      0  0  0
    [torch.DoubleTensor of size 4x3x3]