U PhHe!@sddlmZddlmZmZmZddlZddlZddl m Z m Z m Z m Z mZmZmZmZmZmZmZddlmZmZmZddlmZmZddlmZddlmZed d d \Z Z!d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,g!Z"Gd-ddeZ#Gd.ddeZ$Gd/ddeZ%Gd0ddeZ&Gd1ddeZ'Gd2ddeZ(Gd3d d eZ)Gd4d#d#eZ*Gd5d&d&eZ+Gd6d)d)eZ,Gd7d,d,eZ-e#Z.Z/e$Z0Z1e%Z2Z3e&Z4Z5e'Z6Z7e(Z8Z9e)Z:Z;e*ZZ?e,Z@ZAe-ZBZCdS)8) annotations)CallableHashableMappingN) GenerateDistanceMapGenerateInstanceBorderGenerateInstanceCentroidGenerateInstanceContourGenerateInstanceTypeGenerateSuccinctContourGenerateWatershedMarkersGenerateWatershedMask!HoVerNetInstanceMapPostProcessing!HoVerNetNuclearTypePostProcessing Watershed) DtypeLikeKeysCollectionNdarrayOrTensor) MapTransform Transform)optional_import)HoVerNetBranchzskimage.measure find_contours)name WatershedD WatershedDict WatersheddGenerateWatershedMaskDGenerateWatershedMaskDictGenerateWatershedMaskdGenerateInstanceBorderDGenerateInstanceBorderDictGenerateInstanceBorderdGenerateDistanceMapDGenerateDistanceMapDictGenerateDistanceMapdGenerateWatershedMarkersDGenerateWatershedMarkersDictGenerateWatershedMarkersdGenerateSuccinctContourDictGenerateSuccinctContourDGenerateSuccinctContourdGenerateInstanceContourDictGenerateInstanceContourDGenerateInstanceContourdGenerateInstanceCentroidDictGenerateInstanceCentroidDGenerateInstanceCentroiddGenerateInstanceTypeDictGenerateInstanceTypeDGenerateInstanceTyped%HoVerNetInstanceMapPostProcessingDict"HoVerNetInstanceMapPostProcessingD"HoVerNetInstanceMapPostProcessingd%HoVerNetNuclearTypePostProcessingDict"HoVerNetNuclearTypePostProcessingD"HoVerNetNuclearTypePostProcessingdc sVeZdZdZejZdddejdfddddd d d d fd d ZdddddZ Z S)ra Dictionary-based wrapper of :py:class:`monai.apps.pathology.transforms.array.Watershed`. Use `skimage.segmentation.watershed` to get instance segmentation results from images. See: https://scikit-image.org/docs/stable/api/skimage.segmentation.html#skimage.segmentation.watershed. Args: keys: keys of the corresponding items to be transformed. See also: monai.transforms.MapTransform mask_key: keys of mask used in watershed. Only points at which mask == True will be labeled. markers_key: keys of markers used in watershed. If None (no markers given), the local minima of the image are used as markers. connectivity: An array with the same number of dimensions as image whose non-zero elements indicate neighbors for connection. Following the scipy convention, default is a one-connected array of the dimension of the image. dtype: target data content type to convert. Defaults to np.uint8. allow_missing_keys: don't raise exception if key is missing. Raises: ValueError: when the `image` shape is not [1, H, W]. ValueError: when the `mask` shape is not [1, H, W]. maskNFr str | None int | NonerboolNone)keysmask_key markers_key connectivitydtypeallow_missing_keysreturncs,t||||_||_t||d|_dS)N)rDrE)super__init__rBrCr transform)selfrArBrCrDrErF __class__d/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/apps/pathology/transforms/post/dictionary.pyrIfs zWatershedd.__init__"Mapping[Hashable, NdarrayOrTensor]dict[Hashable, NdarrayOrTensor]datarGcCsZt|}|jr||jnd}|jr,||jnd}||D]}|||||||<q:|SN)dictrCrB key_iteratorrJ)rKrSdmarkersr;keyrNrNrO__call__ts zWatershedd.__call__) __name__ __module__ __qualname____doc__rbackendnpuint8rIrZ __classcell__rNrNrLrOrLs c sZeZdZdZejZddddejdfddd d d d d ddfdd ZdddddZ Z S)ra Dictionary-based wrapper of :py:class:`monai.apps.pathology.transforms.array.GenerateWatershedMask`. Args: keys: keys of the corresponding items to be transformed. mask_key: the mask will be written to the value of `{mask_key}`. activation: the activation layer to be applied on nuclear type branch. It can be "softmax" or "sigmoid" string, or any callable. Defaults to "softmax". threshold: if not None, threshold the float values to int number 0 or 1 with specified threshold. min_object_size: objects smaller than this size are removed. Defaults to 10. dtype: target data content type to convert, default is np.uint8. allow_missing_keys: don't raise exception if key is missing. r;softmaxN Frstrstr | Callable float | Noneintrr?r@)rArB activation thresholdmin_object_sizerErFrGcs*t||||_t||||d|_dS)N)rirjrkrE)rHrIrBr rJ)rKrArBrirjrkrErFrLrNrOrIs zGenerateWatershedMaskd.__init__rPrQrRcCsPt|}||D]8}|||}|j|kr@td|jd|||j<q|S)NzMask with key  already exists.)rUrVrJrBKeyError)rKrSrWrYr;rNrNrOrZs  zGenerateWatershedMaskd.__call__) r[r\r]r^r r_r`rarIrZrbrNrNrLrOrs"c@sLeZdZdZejZddddejfdddddd d d d Zd ddddZ dS)r"a Dictionary-based wrapper of :py:class:`monai.apps.pathology.transforms.array.GenerateInstanceBorder`. Args: mask_key: the input key where the watershed mask is stored. Defaults to `"mask"`. hover_map_key: the input key where hover map is stored. Defaults to `"hover_map"`. border_key: the output key where instance border map is written. Defaults to `"border"`. kernel_size: the size of the Sobel kernel. Defaults to 21. dtype: target data content type to convert, default is np.float32. allow_missing_keys: don't raise exception if key is missing. Raises: ValueError: when the `hover_map` has only one value. ValueError: when the `sobel gradient map` has only one value. r; hover_mapborderrerhrr@)rB hover_map_key border_key kernel_sizerErGcCs$||_||_||_t||d|_dS)N)rsrE)rBrqrrrrJ)rKrBrqrrrsrErNrNrOrIsz GenerateInstanceBorderd.__init__rPrQrRcCsFt|}|j|kr$td|jd|||j||j||j<|S)N The key 'z)' for instance border map already exists.)rUrrrmrJrBrqrKrSrWrNrNrOrZs  z GenerateInstanceBorderd.__call__N) r[r\r]r^rr_r`float32rIrZrNrNrNrOr"s c@sLeZdZdZejZddddejfdddddd d d d Zd ddddZ dS)r%a Dictionary-based wrapper of :py:class:`monai.apps.pathology.transforms.array.GenerateDistanceMap`. Args: mask_key: the input key where the watershed mask is stored. Defaults to `"mask"`. border_key: the input key where instance border map is stored. Defaults to `"border"`. dist_map_key: the output key where distance map is written. Defaults to `"dist_map"`. smooth_fn: smoothing function for distance map, which can be any callable object. If not provided :py:class:`monai.transforms.GaussianSmooth()` is used. dtype: target data content type to convert, default is np.float32. r;roZdist_mapNreCallable | Nonerr@)rBrr dist_map_key smooth_fnrErGcCs$||_||_||_t||d|_dS)N)ryrE)rBrrrxrrJ)rKrBrrrxryrErNrNrOrIszGenerateDistanceMapd.__init__rPrQrRcCsFt|}|j|kr$td|jd|||j||j||j<|S)Nrtz"' for distance map already exists.)rUrxrmrJrBrrrurNrNrOrZs  zGenerateDistanceMapd.__call__) r[r\r]r^rr_r`rvrIrZrNrNrNrOr%s  c @sXeZdZdZejZdddddddejfd d d d d d d d dd ddZdddddZ dS)r(a Dictionary-based wrapper of :py:class:`monai.apps.pathology.transforms.array.GenerateWatershedMarkers`. Args: mask_key: the input key where the watershed mask is stored. Defaults to `"mask"`. border_key: the input key where instance border map is stored. Defaults to `"border"`. markers_key: the output key where markers is written. Defaults to `"markers"`. threshold: threshold the float values of instance border map to int 0 or 1 with specified threshold. It turns uncertain area to 1 and other area to 0. Defaults to 0.4. radius: the radius of the disk-shaped footprint used in `opening`. Defaults to 2. min_object_size: objects smaller than this size are removed. Defaults to 10. postprocess_fn: execute additional post transformation on marker. Defaults to None. dtype: target data content type to convert, default is np.uint8. allow_missing_keys: don't raise exception if key is missing. r;rorX皙?rdNrefloatrhrwrr@) rBrrrCrjradiusrkpostprocess_fnrErGc Cs*||_||_||_t|||||d|_dS)N)rjr}rkr~rE)rBrrrCr rJ) rKrBrrrCrjr}rkr~rErNrNrOrI s z"GenerateWatershedMarkersd.__init__rPrQrRcCsFt|}|j|kr$td|jd|||j||j||j<|S)Nrtz' for markers already exists.)rUrCrmrJrBrrrurNrNrOrZ!s  z"GenerateWatershedMarkersd.__call__) r[r\r]r^r r_r`rarIrZrNrNrNrOr(s cs>eZdZdZejZd ddddddfdd Zd d ZZS) r+a Dictionary-based wrapper of :py:class:`monai.apps.pathology.transforms.post.array.GenerateSuccinctContour`. Converts SciPy-style contours (generated by skimage.measure.find_contours) to a more succinct version which only includes the pixels to which lines need to be drawn (i.e. not the intervening pixels along each line). Args: keys: keys of the corresponding items to be transformed. height: height of bounding box, used to detect direction of line segment. width: width of bounding box, used to detect direction of line segment. allow_missing_keys: don't raise exception if key is missing. Frrhr?r@)rAheightwidthrFrGcs t||t||d|_dS)N)rr)rHrIr converter)rKrArrrFrLrNrOrI9sz!GenerateSuccinctContourd.__init__cCs.t|}||D]}|||||<q|SrT)rUrVr)rKrSrWrYrNrNrOrZ=sz!GenerateSuccinctContourd.__call__)F) r[r\r]r^r r_rIrZrbrNrNrLrOr+)s c sBeZdZdZejZddddd d d d d fdd ZddZZS)r.a Dictionary-based wrapper of :py:class:`monai.apps.pathology.transforms.post.array.GenerateInstanceContour`. Generate contour for each instance in a 2D array. Use `GenerateSuccinctContour` to only include the pixels to which lines need to be drawn Args: keys: keys of the corresponding items to be transformed. contour_key_postfix: the output contour coordinates will be written to the value of `{key}_{contour_key_postfix}`. offset_key: keys of offset used in `GenerateInstanceContour`. min_num_points: assumed that the created contour does not form a contour if it does not contain more points than the specified value. Defaults to 3. level: optional. Value along which to find contours in the array. By default, the level is set to (max(image) + min(image)) / 2. allow_missing_keys: don't raise exception if key is missing. contourNFrrer=rhrgr?r@)rAcontour_key_postfix offset_keymin_num_pointslevelrFrGcs,t||t||d|_||_||_dS)N)r contour_level)rHrIr rrr)rKrArrrrrFrLrNrOrIZs z!GenerateInstanceContourd.__init__cCspt|}||D]X}|jr&||jnd}||||}|d|j}||krbtd|d|||<q|S)N_zContour with key rl)rUrVrrrrm)rKrSrWrYoffsetr key_to_addrNrNrOrZhs z!GenerateInstanceContourd.__call__)rNrNF) r[r\r]r^r r_rIrZrbrNrNrLrOr.Es csHeZdZdZejZddedfddddd d d fd d ZddZZ S)r1aK Dictionary-based wrapper of :py:class:`monai.apps.pathology.transforms.post.array.GenerateInstanceCentroid`. Generate instance centroid using `skimage.measure.centroid`. Args: keys: keys of the corresponding items to be transformed. centroid_key_postfix: the output centroid coordinates will be written to the value of `{key}_{centroid_key_postfix}`. offset_key: keys of offset used in `GenerateInstanceCentroid`. dtype: the data type of output centroid. allow_missing_keys: don't raise exception if key is missing. centroidNFrrer=zDtypeLike | Noner?r@)rAcentroid_key_postfixrrErFrGcs*t||t|d|_||_||_dS)N)rE)rHrIrrrr)rKrArrrErFrLrNrOrIs z"GenerateInstanceCentroidd.__init__cCspt|}||D]X}|jr&||jnd}||||}|d|j}||krbtd|d|||<q|S)NrzCentroid with key rl)rUrVrrrrm)rKrSrWrYrrrrNrNrOrZs z"GenerateInstanceCentroidd.__call__) r[r\r]r^rr_rhrIrZrbrNrNrLrOr1ts c sBeZdZdZejZddddddd d d fd d ZddZZS)r4aR Dictionary-based wrapper of :py:class:`monai.apps.pathology.transforms.post.array.GenerateInstanceType`. Generate instance type and probability for each instance. Args: keys: keys of the corresponding items to be transformed. type_info_key: the output instance type and probability will be written to the value of `{type_info_key}`. bbox_key: keys of bounding box. seg_pred_key: keys of segmentation prediction map. instance_id_key: keys of instance id. allow_missing_keys: don't raise exception if key is missing. type_infobboxsegidFrrer?r@)rA type_info_keybbox_key seg_pred_keyinstance_id_keyrFrGcs2t||t|_||_||_||_||_dSrT)rHrIr rrrrr)rKrArrrrrFrLrNrOrIs zGenerateInstanceTyped.__init__c Cst|}||D]h}||j}||j}||j}||||||\}}|j} | |krltd| d||d|| <q|S)NzType information with key rl) inst_type type_prob)rUrVrrrrrrm) rKrSrWrYrrr instance_typerrrNrNrOrZs   zGenerateInstanceTyped.__call__)rrrrF) r[r\r]r^r r_rIrZrbrNrNrLrOr4s csxeZdZdZejjejjddddddddd dd d ddfd d d d d dddddddddddddfdd ZddZ Z S)r7a] Dictionary-based wrapper for :py:class:`monai.apps.pathology.transforms.post.array.HoVerNetInstanceMapPostProcessing`. The post-processing transform for HoVerNet model to generate instance segmentation map. It generates an instance segmentation map as well as a dictionary containing centroids, bounding boxes, and contours for each instance. Args: nuclear_prediction_key: the key for HoVerNet NP (nuclear prediction) branch. Defaults to `HoVerNetBranch.NP`. hover_map_key: the key for HoVerNet NC (nuclear prediction) branch. Defaults to `HoVerNetBranch.HV`. instance_info_key: the output key where instance information (contour, bounding boxes, and centroids) is written. Defaults to `"instance_info"`. instance_map_key: the output key where instance map is written. Defaults to `"instance_map"`. activation: the activation layer to be applied on the input probability map. It can be "softmax" or "sigmoid" string, or any callable. Defaults to "softmax". mask_threshold: a float value to threshold to binarize probability map to generate mask. min_object_size: objects smaller than this size are removed. Defaults to 10. sobel_kernel_size: the size of the Sobel kernel used in :py:class:`GenerateInstanceBorder`. Defaults to 5. distance_smooth_fn: smoothing function for distance map. If not provided, :py:class:`monai.transforms.intensity.GaussianSmooth()` will be used. marker_threshold: a float value to threshold to binarize instance border map for markers. It turns uncertain area to 1 and other area to 0. Defaults to 0.4. marker_radius: the radius of the disk-shaped footprint used in `opening` of markers. Defaults to 2. marker_postprocess_fn: post-process function for watershed markers. If not provided, :py:class:`monai.transforms.post.FillHoles()` will be used. watershed_connectivity: `connectivity` argument of `skimage.segmentation.watershed`. min_num_points: minimum number of points to be considered as a contour. Defaults to 3. contour_level: an optional value for `skimage.measure.find_contours` to find contours in the array. If not provided, the level is set to `(max(image) + min(image)) / 2`. device: target device to put the output Tensor data. instance_info instance_maprcNrdrzr{r<rrerfrgrhrwr|r>str | torch.device | Noner@)nuclear_prediction_keyrqinstance_info_keyinstance_map_keyrimask_thresholdrksobel_kernel_sizedistance_smooth_fnmarker_threshold marker_radiusmarker_postprocess_fnwatershed_connectivityrrdevicerGcsHtt||||| | | | | |||d |_||_||_||_||_dS)N) rirrkrrrrrrrrr)rHrIrinstance_map_post_processrrqrr)rKrrqrrrirrkrrrrrrrrrrLrNrOrIs& z+HoVerNetInstanceMapPostProcessingd.__init__cCsVt|}|j|jfD]}||krtdq|||j||j\||j<||j<|S)Nz>The output key ['{k}'] already exists in the input dictionary!)rUrr ValueErrorrrrq)rKrSrWkrNrNrOrZs z+HoVerNetInstanceMapPostProcessingd.__call__) r[r\r]r^rNPvalueHVrIrZrbrNrNrLrOr7s&!4'c sTeZdZdZejjdddddddfddddd d d d d d fdd ZddZZ S)r:aY Dictionary-based wrapper for :py:class:`monai.apps.pathology.transforms.post.array.HoVerNetNuclearTypePostProcessing`. It updates the input instance info dictionary with information about types of the nuclei (value and probability). Also if requested (`return_type_map=True`), it generates a pixel-level type map. Args: type_prediction_key: the key for HoVerNet NC (type prediction) branch. Defaults to `HoVerNetBranch.NC`. instance_info_key: the key where instance information (contour, bounding boxes, and centroids) is stored. Defaults to `"instance_info"`. instance_map_key: the key where instance map is stored. Defaults to `"instance_map"`. type_map_key: the output key where type map is written. Defaults to `"type_map"`. device: target device to put the output Tensor data. rrtype_maprcNTrerfrgr?rr@) type_prediction_keyrr type_map_keyrirjreturn_type_maprrGc s>tt||||d|_||_||_||_||_||_dS)N)rirjrr) rHrIrtype_post_processrrrrr) rKrrrrrirjrrrLrNrOrI3s z+HoVerNetNuclearTypePostProcessingd.__init__cCsXt|}|||j||j||j\||j<}|jrT|j|krJtd|||j<|S)NzNThe output key ['{self.type_map_key}'] already exists in the input dictionary!)rUrrrrrrr)rKrSrWrrNrNrOrZHs  z+HoVerNetNuclearTypePostProcessingd.__call__) r[r\r]r^rNCrrIrZrbrNrNrLrOr:#s$)D __future__rcollections.abcrrrnumpyr`torchZ*monai.apps.pathology.transforms.post.arrayrrrr r r r r rrrmonai.config.type_definitionsrrrmonai.transforms.transformrr monai.utilsrmonai.utils.enumsrrr__all__rrr"r%r(r+r.r1r4r7r:rrrrr r!r#r$r&r'r)r*r,r-r/r0r2r3r5r6r8r9rNrNrNrO s 4   %3,)$1/*0U3