o  i5@sddlmZddlmZddlZddlmZddlmZm Z ddl m Z m Z m Z e ddd \ZZd d gZGd d d eZ    d.d/dd Zd0d d!Z "d1d2d&d'Z "d3d4d*d+Zd5d,d-ZdS)6) annotations)SequenceN)CumulativeIterationMetric)do_metric_reductionremap_instance_id)MetricReduction ensure_tupleoptional_importzscipy.optimizelinear_sum_assignment)namePanopticQualityMetriccompute_panoptic_qualitycsDeZdZdZdejddfdfdd ZdddZddddZZ S) r a Compute Panoptic Quality between two instance segmentation masks. If specifying `metric_name` to "SQ" or "RQ", Segmentation Quality (SQ) or Recognition Quality (RQ) will be returned instead. Panoptic Quality is a metric used in panoptic segmentation tasks. This task unifies the typically distinct tasks of semantic segmentation (assign a class label to each pixel) and instance segmentation (detect and segment each object instance). Compared with semantic segmentation, panoptic segmentation distinguish different instances that belong to same class. Compared with instance segmentation, panoptic segmentation does not allow overlap and only one semantic label and one instance id can be assigned to each pixel. Please refer to the following paper for more details: https://openaccess.thecvf.com/content_CVPR_2019/papers/Kirillov_Panoptic_Segmentation_CVPR_2019_paper.pdf This class also refers to the following implementation: https://github.com/TissueImageAnalytics/CoNIC Args: num_classes: number of classes. The number should not count the background. metric_name: output metric. The value can be "pq", "sq" or "rq". Except for input only one metric, multiple metrics are also supported via input a sequence of metric names such as ("pq", "sq", "rq"). If input a sequence, a list of results with the same order as the input names will be returned. reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values, available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, ``"mean_channel"``, ``"sum_channel"``}, default to `self.reduction`. if "none", will not do reduction. match_iou_threshold: IOU threshold to determine the pairing between `y_pred` and `y`. Usually, it should >= 0.5, the pairing between instances of `y_pred` and `y` are identical. If set `match_iou_threshold` < 0.5, this function uses Munkres assignment to find the maximal amount of unique pairing. smooth_numerator: a small constant added to the numerator to avoid zero. pq?ư> num_classesint metric_nameSequence[str] | str reductionMetricReduction | strmatch_iou_thresholdfloatsmooth_numeratorreturnNonecs0t||_||_||_||_t||_dSN)super__init__rrrrrr)selfrrrrr __class__`/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/metrics/panoptic_quality.pyr=s zPanopticQualityMetric.__init__y_pred torch.Tensoryc Cs|j|jkrtd|jd|jd|jddkr%td|jdd|}|dkr5td|d|jd }tj||jdg|jd }t|D]B}||d f||d f}}||df||df} } t|jD] } | | dk|} | | dk|} t| | d |j d d ||| f<qkqJ|S) aV Args: y_pred: Predictions. It must be in the form of B2HW and have integer type. The first channel and the second channel represent the instance predictions and classification predictions respectively. y: ground truth. It must have the same shape as `y_pred` and have integer type. The first channel and the second channel represent the instance labels and classification labels respectively. Values in the second channel of `y_pred` and `y` should be in the range of 0 to `self.num_classes`, where 0 represents the background. Raises: ValueError: when `y_pred` and `y` have different shapes. ValueError: when `y_pred` and `y` have != 2 channels. ValueError: when `y_pred` and `y` have != 4 dimensions. z*y_pred and y should have same shapes, got  and .zJfor panoptic quality calculation, only 2 channels input is supported, got z6y_pred should have 4 dimensions (batch, 2, h, w), got rdeviceT)predgtremaproutput_confusion_matrix) shape ValueError ndimensiontorchzerosrr-ranger r)rr$r&dims batch_sizeoutputsbZ true_instanceZ pred_instanceZ true_classZ pred_classcZpred_instance_cZtrue_instance_cr"r"r#_compute_tensorLs4    z%PanopticQualityMetric._compute_tensorNMetricReduction | str | None!torch.Tensor | list[torch.Tensor]c Cs|}t|tjstdt||p|j\}}|d|d|d|df\}}}}g} |jD]>} t| } | dkrL| ||d|d||j q/| dkr[| |||j q/| ||d|d||j q/t | d krx| d S| S) a Execute reduction logic for the output of `compute_panoptic_quality`. Args: reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values, available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, ``"mean_channel"``, ``"sum_channel"``}, default to `self.reduction`. if "none", will not do reduction. z-the data to aggregate must be PyTorch Tensor.).r).r)).r*).rqrsqr)r) get_buffer isinstancer5Tensorr3rrr_check_panoptic_metric_nameappendrlen) rrdataf_tpfpfniou_sumresultsrr"r"r# aggregate}s $ &&zPanopticQualityMetric.aggregate) rrrrrrrrrrrr)r$r%r&r%rr%r)rr>rr?) __name__ __module__ __qualname____doc__r MEAN_BATCHrr=rQ __classcell__r"r"r r#r s$ 1rTrrFr.r%r/rstrr0boolrrrr1rcs|j|jkrtd|jd|jd|dks|dkr#td|d|}|}|dur7t|}t|}t|||jd\}}} t|||jd\} fd d |d d D} fd d | d d D} tt| t| } }}| }|rt j | |||g|jdSt |}|dkrt j | | d|d|||jdS|dkrt j || ||jdSt j || d|d|||jdS)avComputes Panoptic Quality (PQ). If specifying `metric_name` to "SQ" or "RQ", Segmentation Quality (SQ) or Recognition Quality (RQ) will be returned instead. In addition, if `output_confusion_matrix` is True, the function will return a tensor with shape 4, which represents the true positive, false positive, false negative and the sum of iou. These four values are used to calculate PQ, and returning them directly enables further calculation over all images. Args: pred: input data to compute, it must be in the form of HW and have integer type. gt: ground truth. It must have the same shape as `pred` and have integer type. metric_name: output metric. The value can be "pq", "sq" or "rq". remap: whether to remap `pred` and `gt` to ensure contiguous ordering of instance id. match_iou_threshold: IOU threshold to determine the pairing between `pred` and `gt`. Usually, it should >= 0.5, the pairing between instances of `pred` and `gt` are identical. If set `match_iou_threshold` < 0.5, this function uses Munkres assignment to find the maximal amount of unique pairing. smooth_numerator: a small constant added to the numerator to avoid zero. Raises: ValueError: when `pred` and `gt` have different shapes. ValueError: when `match_iou_threshold` <= 0.0 or > 1.0. z)pred and gt should have same shapes, got r'r(g?z4'match_iou_threshold' should be within (0, 1], got: Tr,cg|]}|vr|qSr"r".0idx) paired_truer"r# z,compute_panoptic_quality..r)Ncr[r"r"r\) paired_predr"r#r`rarArrB) r2r3rr_get_pairwise_iour-_get_paired_iourHsumr5 as_tensorrF)r.r/rr0rrr1 pairwise_iou true_id_list pred_id_list paired_iouZ unpaired_trueZ unpaired_predrLrMrNrOr")rbr_r#r s2 ! ((list[torch.Tensor]cCs.t|}d|vr|dtd|S)Nr)listuniqueinsertr5tensorr)r/Zid_listr"r"r# _get_id_lists rpcpur-str | torch.device;tuple[torch.Tensor, list[torch.Tensor], list[torch.Tensor]]cCs<t|}t|}tjt|dt|dgtj|d}g}g}|ddD]}tj||k|d} || q%|ddD]} tj|| k|d} || q>tdt|D]@} || d} || dk} t | }|D])}|dkruqn||d} | |  }| |  }|||}||| d|df<qnqX|||fS)Nr))dtyper-r,r) rpr5r6rHrrfrrGr7rlrmre)r.r/r-rirhrgZ true_masksZ pred_maskstZt_maskpZp_maskZtrue_idZpred_true_overlapZpred_true_overlap_idpred_idtotalinteriour"r"r#rcs2&          rcrg/tuple[torch.Tensor, torch.Tensor, torch.Tensor]cCs|dkr4d|||k<t|dddft|dddf}}|||f}|d7}|d7}|||fS|}t| \}}|||f}tjt|||kd|d}tjt|||kd|d}|||k}|||fS)NrrZrr)r,)r5nonzerorqnumpyr rfrl)rgrr-r_rbrjr"r"r#rd s .      rdcCsH|dd}|}|dvrdS|dvrdS|dvrdStd |d ) N rK)panoptic_qualityrr)Zsegmentation_qualityrBrB)Zrecognition_qualityrArAz metric name: z) is wrong, please use 'pq', 'sq' or 'rq'.)replacelowerr3)rr"r"r#rFs rF)rTrrF)r.r%r/r%rrXr0rYrrrrr1rYrr%)r/r%rrk)rq)r.r%r/r%r-rrrrs)rrq)rgr%rrr-rrrr{)rrXrrX) __future__rcollections.abcrr5Zmonai.metrics.metricrmonai.metrics.utilsrr monai.utilsrrr r rK__all__r r rprcrdrFr"r"r"r#s,   C #