def normal_to_grad_depth()

in pytouch/tasks/surface3d/geometry.py [0:0]


def normal_to_grad_depth(img_normal, gel_width=1.0, gel_height=1.0, bg_mask=None):
    # Ref: https://stackoverflow.com/questions/34644101/calculate-surface-normals-from-depth-image-using-neighboring-pixels-cross-produc/34644939#34644939 # noqa: E501

    EPS = 1e-1
    nz = torch.max(torch.tensor(EPS), img_normal[2, :])

    dzdx = -(img_normal[0, :] / nz).squeeze()
    dzdy = -(img_normal[1, :] / nz).squeeze()

    # taking out negative sign as we are computing gradient of depth not z
    # since z is pointed towards sensor, increase in z corresponds to decrease in depth
    # i.e., dz/dx = -ddepth/dx
    ddepthdx = -dzdx
    ddepthdy = -dzdy

    # sim: pixel axis v points in opposite dxn of camera axis y
    ddepthdu = ddepthdx
    ddepthdv = -ddepthdy

    gradx = ddepthdu  # cols
    grady = ddepthdv  # rows

    # convert units from pixel to meters
    C, H, W = img_normal.shape
    gradx = gradx * (gel_width / W)
    grady = grady * (gel_height / H)

    if bg_mask is not None:
        gradx = mask_background(gradx, bg_mask=bg_mask, bg_val=0.0)
        grady = mask_background(grady, bg_mask=bg_mask, bg_val=0.0)

    return gradx, grady