Skip to content

Fliptate Solution


flipped = torch.flip(img, dims=(1,))
rotated = torch.rot90(flipped, k=-1)

Explanation

  1. First we flip the image using torch.flip().

    flipped = torch.flip(img, dims=(1,))
    

    dims identifies which dimensions (axes) to flip. Flipping the image horizontally means flipping the column indices which are stored in dimension 1. (Remember, the image dimensions represent rows by columns by color channels.)

  2. Next we rotate the image using torch.rot90().

    rotated = torch.rot90(flipped, k=-1)
    

    The docs for rot90 explain the k parameter as follows:

    number of times to rotate. Rotation direction is from the first towards the second axis if k > 0, and from the second towards the first for k < 0.

    The axes for img look like this:

                               axis 1:
                   0   1   2   3   4   5   6   7
                  ------------------------------> 
             0 | [[0., 0., 0., 0., 0., 0., 0., 0.],
             1 |  [0., 0., 0., 0., 0., 0., 0., 0.],
             2 |  [0., 0., 1., 0., 0., 1., 0., 0.],
    axis 0:  3 |  [0., 0., 1., 0., 0., 1., 0., 0.],
             4 |  [0., 0., 1., 1., 1., 1., 0., 0.],
             5 |  [0., 0., 1., 0., 0., 0., 0., 0.],
             6 |  [0., 0., 1., 0., 0., 0., 0., 0.],
             7 ∨  [0., 0., 1., 0., 0., 0., 0., 0.]]
    
    • k=1 means rotate once from axis 0 towards axis 1, which corresponds to a 90-degree counter-clockwise rotation.
    • k=-1 means rotate once from axis 1 towards axis 0, which corresponds to a 90-degree clockwise rotation.