a vK6d@sdZddlZddlmZddZddZdd Zd d Zd d ZddZ ddZ e dkre ddZ e ddZee e\ZZddlZedS)z3 Utilities for bounding box manipulation and GIoU. N)box_areacCsL|d\}}}}|d||d||d||d|g}tj|ddS)Ng?dimunbindtorchstack)xx_cy_cwhbr/mnt/e/Liuyz_DL_and_ML/jupyter_notebook/python_CVs/Grounded-Segment-Anything_huggingface_yizhangliu/GroundingDINO/groundingdino/util/box_ops.pybox_cxcywh_to_xyxy s,rcCsD|d\}}}}||d||d||||g}tj|ddS)Nrrr)r x0y0x1y1rrrrbox_xyxy_to_cxcywhs$rc Cst|}t|}t|dddddf|ddddf}t|dddddf|ddddf}||jdd}|dddddf|dddddf}|dddf||}||d} | |fS)Nrrminư>rrmaxrclamp boxes1boxes2area1area2ltrbwhinterunioniourrrbox_ious.., r+cCs|ddddf|ddddfks0J|ddddf|ddddfks`Jt||\}}t|dddddf|ddddf}t|dddddf|ddddf}||jdd}|dddddf|dddddf}||||dS)z Generalized IoU from https://giou.stanford.edu/ The boxes should be in [x0, y0, x1, y1] format Returns a [N, M] pairwise matrix, where N = len(boxes1) and M = len(boxes2) Nrrrrr)allr+rrrrr!r"r*r)r%r&r'arearrrgeneralized_box_iou's 00..,r/c Cst|}t|}t|ddddf|ddddf}t|ddddf|ddddf}||jdd}|dddf|dddf}|||}||} | |fS)Nrrrrrr rrrbox_iou_pairwiseBs,,  r0cCs|ddddf|ddddfks0J|ddddf|ddddfks`J|j|jkspJt||\}}t|ddddf|ddddf}t|ddddf|ddddf}||jdd}|dddf|dddf}||||S)z Generalized IoU from https://giou.stanford.edu/ Input: - boxes1, boxes2: N,4 Output: - giou: N, 4 Nrrrr)r,shaper0rrrrr-rrrgeneralized_box_iou_pairwiseRs 00,, r2c Cs|dkrtjd|jdS|jdd\}}tjd|tjd}tjd|tjd}t||\}}||d}| d dd}| | d  d dd}||d}| d dd} | | d  d dd} t|| || gdS) zCompute the bounding boxes around the provided masks The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions. Returns a [N, 4] tensors, with the boxes in xyxy format r)r)deviceN)dtyperrgחA)numelrzerosr4r1arangefloatmeshgrid unsqueezeflattenr masked_fillboolrr ) masksrr yr Zx_maskx_maxx_minZy_masky_maxy_minrrrmasks_to_boxesks ""rF__main__r3)__doc__rZtorchvision.ops.boxesrrrr+r/r0r2rF__name__randr rAr*r)Zipdb set_tracerrrrs