Search code examples
pythonnumpydeep-learningpytorch

How to slice Torch images as numpy images


I am working on a problem in which I have the coordinates to slice the image like

X cordinate, Y coordinate, Height, width of the region to crop

So if if I have torch image obtained using

img = Variable(img.cuda())

how can we slice this image to get that specific area of image [y:y+height, x:x+width] . Thanks


Solution

  • If I understand your question correctly, then you can do it just the same way as in numpy.

    Here is a short example:

    import torch
    t = torch.rand(5, 5)
    # original matrix
    print(t)
    h = 2
    w = 2
    x = 1
    y = 1
    # cropped out matrix
    print(t[x:x+h, y:y+w])
    

    Output:

    tensor([[ 0.5402,  0.4106,  0.9904,  0.9556,  0.2217],
            [ 0.4533,  0.6300,  0.5352,  0.2710,  0.4307],
            [ 0.6389,  0.5660,  0.1582,  0.5701,  0.1614],
            [ 0.1717,  0.4071,  0.4960,  0.2127,  0.5587],
            [ 0.9529,  0.2865,  0.6667,  0.7401,  0.3372]])
    tensor([[ 0.6300,  0.5352],
            [ 0.5660,  0.1582]])
    

    As you can see a 2x2 matrix is cropped out of t.