Get corner of rectangle near to origin in batch of tensor given any two diagonal coordinates in pytorch
Let's say I have pytorch tensor of batch of coordinates of off diagonal elements and I want to get coordinate of the corner which is near to origin. coordinates are in (x1, y1, x2, y2) form.

a = torch.tensor([[3,2,2,3], [1,1,2,2])
# expected output
[[2,2], [1,1]]


You can just iterate over all tensors and for each of them calculate distance to four corners and take the corner with minimum distance.

import torch
a = torch.tensor([[3,2,2,3], [1,1,2,2]])
c = torch.zeros(a.shape[0], 2)
for idx, x in enumerate(a):
    d1 = x[0] ** 2 + x[1] ** 2
    d2 = x[2] ** 2 + x[3] ** 2
    d3 = x[0] ** 2 + x[3] ** 2
    d4 = x[2] ** 2 + x[1] ** 2
    dmin = min(d1, d2, d3, d4)
    if d1 == dmin:
        c[idx] = torch.tensor([x[0], x[1]])
    elif d2 == dmin:
        c[idx] = torch.tensor([x[2], x[3]])
    elif d3 == dmin:
        c[idx] = torch.tensor([x[0], x[3]])
    elif d4 == dmin:
        c[idx] = torch.tensor([x[2], x[1]])
print(c)  # tensor([[2., 2.], [1., 1.]])

