Ben Gorman

Ben Gorman

Life's a garden. Dig it.

Challenge

Given an 8x8x3 tensor which represents an image of the number 4,

Flip the image horizontally.

Then rotate the image clockwise 90 degrees.

import torch
 
r = torch.tensor([
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0],
    [0,0,1,0,0,1,0,0],
    [0,0,1,0,0,1,0,0],
    [0,0,1,1,1,1,0,0],
    [0,0,0,0,0,1,0,0],
    [0,0,0,0,0,1,0,0],
    [0,0,0,0,0,1,0,0]
], dtype=torch.float32)
g = 0.8*r
b = 0.5*r
img = torch.moveaxis(torch.stack((r,g,b)), 0, -1)
 
print(img.shape)
# torch.Size([8, 8, 3]) (1)
  1. img is an 8x8 image with 3 color channels (RGB).

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.