def crop_image(joints, im, Xlabel, Ylabel, cfg):
"""Randomly cropping image around xlabel,ylabel taking into account size of image.
Introduced in DLC 2.0 (Nature Protocols paper)
"""
widthforward = int(cfg["minsize"] + np.random.randint(cfg["rightwidth"]))
widthback = int(cfg["minsize"] + np.random.randint(cfg["leftwidth"]))
hup = int(cfg["minsize"] + np.random.randint(cfg["topheight"]))
hdown = int(cfg["minsize"] + np.random.randint(cfg["bottomheight"]))
Xstart = max(0, int(Xlabel - widthback))
Xstop = min(np.shape(im)[1] - 1, int(Xlabel + widthforward))
Ystart = max(0, int(Ylabel - hdown))
Ystop = min(np.shape(im)[0] - 1, int(Ylabel + hup))
joints[0, :, 1] -= Xstart
joints[0, :, 2] -= Ystart
inbounds = np.where(
(joints[0, :, 1] > 0)
* (joints[0, :, 1] < np.shape(im)[1])
* (joints[0, :, 2] > 0)
* (joints[0, :, 2] < np.shape(im)[0])
)[0]
return joints[:, inbounds, :], im[Ystart : Ystop + 1, Xstart : Xstop + 1, :]