o  iHe@sddlmZddlmZmZmZddlZddlZddl m Z m Z m Z m Z mZmZmZmZmZmZmZddlmZmZmZddlmZmZddlmZddlmZed d d \Z Z!gd Z"Gd ddeZ#GdddeZ$GdddeZ%GdddeZ&GdddeZ'GdddeZ(GdddeZ)GdddeZ*GdddeZ+Gdd d eZ,Gd!d"d"eZ-e#Z.Z/e$Z0Z1e%Z2Z3e&Z4Z5e'Z6Z7e(Z8Z9e)Z:Z;e*ZZ?e,Z@ZAe-ZBZCdS)#) annotations)CallableHashableMappingN) GenerateDistanceMapGenerateInstanceBorderGenerateInstanceCentroidGenerateInstanceContourGenerateInstanceTypeGenerateSuccinctContourGenerateWatershedMarkersGenerateWatershedMask!HoVerNetInstanceMapPostProcessing!HoVerNetNuclearTypePostProcessing Watershed) DtypeLikeKeysCollectionNdarrayOrTensor) MapTransform Transform)optional_import)HoVerNetBranchzskimage.measure find_contours)name)! WatershedD WatershedDict WatersheddGenerateWatershedMaskDGenerateWatershedMaskDictGenerateWatershedMaskdGenerateInstanceBorderDGenerateInstanceBorderDictGenerateInstanceBorderdGenerateDistanceMapDGenerateDistanceMapDictGenerateDistanceMapdGenerateWatershedMarkersDGenerateWatershedMarkersDictGenerateWatershedMarkersdGenerateSuccinctContourDictGenerateSuccinctContourDGenerateSuccinctContourdGenerateInstanceContourDictGenerateInstanceContourDGenerateInstanceContourdGenerateInstanceCentroidDictGenerateInstanceCentroidDGenerateInstanceCentroiddGenerateInstanceTypeDictGenerateInstanceTypeDGenerateInstanceTyped%HoVerNetInstanceMapPostProcessingDict"HoVerNetInstanceMapPostProcessingD"HoVerNetInstanceMapPostProcessingd%HoVerNetNuclearTypePostProcessingDict"HoVerNetNuclearTypePostProcessingD"HoVerNetNuclearTypePostProcessingdcs@eZdZdZejZdddejdfdfdd ZdddZ 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]. maskNFkeysrmask_key str | None markers_key connectivity int | Nonedtyperallow_missing_keysboolreturnNonecs,t||||_||_t||d|_dS)N)rArC)super__init__r>r@r transform)selfr=r>r@rArCrD __class__q/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/apps/pathology/transforms/post/dictionary.pyrIfs zWatershedd.__init__data"Mapping[Hashable, NdarrayOrTensor]dict[Hashable, NdarrayOrTensor]cCsZt|}|jr ||jnd}|jr||jnd}||D] }|||||||<q|SN)dictr@r> key_iteratorrJ)rKrPdmarkersr;keyrNrNrO__call__ts zWatershedd.__call__)r=rr>r?r@r?rArBrCrrDrErFrGrPrQrFrR) __name__ __module__ __qualname____doc__rbackendnpuint8rIrY __classcell__rNrNrLrOrLsrcsBeZdZdZejZddddejdfdfdd ZdddZ 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 Fr=rr>str activationstr | Callable threshold float | Nonemin_object_sizeintrCrrDrErFrGcs*t||||_t||||d|_dS)N)rfrhrjrC)rHrIr>r rJ)rKr=r>rfrhrjrCrDrLrNrOrIs   zGenerateWatershedMaskd.__init__rPrQrRcCsPt|}||D]}|||}|j|vr td|jd|||j<q |S)NzMask with key  already exists.)rTrUrJr>KeyError)rKrPrVrXr;rNrNrOrYs  zGenerateWatershedMaskd.__call__)r=rr>rerfrgrhrirjrkrCrrDrErFrGrZ) r[r\r]r^r r_r`rarIrYrbrNrNrLrOrsrc@s8eZdZdZejZddddejfdddZdddZ 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_mapborderr>re hover_map_key border_key kernel_sizerkrCrrFrGcC$||_||_||_t||d|_dS)N)rsrC)r>rqrrrrJ)rKr>rqrrrsrCrNrNrOrIz GenerateInstanceBorderd.__init__rPrQrRcCFt|}|j|vrtd|jd|||j||j||j<|S)N The key 'z)' for instance border map already exists.)rTrrrmrJr>rqrKrPrVrNrNrOrY  z GenerateInstanceBorderd.__call__N) r>rerqrerrrersrkrCrrFrGrZ) r[r\r]r^rr_r`float32rIrYrNrNrNrOr"s  r"c@s8eZdZdZejZddddejfdddZdddZ 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_mapNr>rerr dist_map_key smooth_fnCallable | NonerCrrFrGcCrt)N)r|rC)r>rrr{rrJ)rKr>rrr{r|rCrNrNrOrIruzGenerateDistanceMapd.__init__rPrQrRcCrv)Nrwz"' for distance map already exists.)rTr{rmrJr>rrrxrNrNrOrYryzGenerateDistanceMapd.__call__) r>rerrrer{rer|r}rCrrFrGrZ) r[r\r]r^rr_r`rzrIrYrNrNrNrOr%s   r%c@s>eZdZdZejZdddddddejfdddZd ddZ 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;rorW皙?rdNr>rerrr@rhfloatradiusrkrjpostprocess_fnr}rCrrFrGc Cs*||_||_||_t|||||d|_dS)N)rhrrjrrC)r>rrr@r rJ) rKr>rrr@rhrrjrrCrNrNrOrI s  z"GenerateWatershedMarkersd.__init__rPrQrRcCrv)Nrwz' for markers already exists.)rTr@rmrJr>rrrxrNrNrOrY!ryz"GenerateWatershedMarkersd.__call__)r>rerrrer@rerhrrrkrjrkrr}rCrrFrGrZ) r[r\r]r^r r_r`rarIrYrNrNrNrOr(s r(cs2eZdZdZejZddfd d ZddZZS)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. Fr=rheightrkwidthrDrErFrGcs t||t||d|_dS)N)rr)rHrIr converter)rKr=rrrDrLrNrOrI9sz!GenerateSuccinctContourd.__init__cCs.t|}||D] }|||||<q |SrS)rTrUr)rKrPrVrXrNrNrOrY=sz!GenerateSuccinctContourd.__call__)F) r=rrrkrrkrDrErFrG) r[r\r]r^r r_rIrYrbrNrNrLrOr+)s  r+cs<eZdZdZejZ     ddfdd 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. contourNFr=rcontour_key_postfixre offset_keyr?min_num_pointsrklevelrirDrErFrGcs,t||t||d|_||_||_dS)N)r contour_level)rHrIr rrr)rKr=rrrrrDrLrNrOrIZs  z!GenerateInstanceContourd.__init__cCpt|}||D],}|jr||jnd}||||}|d|j}||vr1td|d|||<q |S)N_zContour with key rl)rTrUrrrrm)rKrPrVrXoffsetr key_to_addrNrNrOrYh z!GenerateInstanceContourd.__call__)rNrNF)r=rrrerr?rrkrrirDrErFrG) r[r\r]r^r r_rIrYrbrNrNrLrOr.Esr.cs:eZdZdZejZddedfdfdd 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. centroidNFr=rcentroid_key_postfixrerr?rCDtypeLike | NonerDrErFrGcs*t||t|d|_||_||_dS)N)rC)rHrIrrrr)rKr=rrrCrDrLrNrOrIs  z"GenerateInstanceCentroidd.__init__cCr)NrzCentroid with key rl)rTrUrrrrm)rKrPrVrXrrrrNrNrOrYrz"GenerateInstanceCentroidd.__call__) r=rrrerr?rCrrDrErFrG) r[r\r]r^rr_rkrIrYrbrNrNrLrOr1ts r1cs<eZdZdZejZ     ddfdd 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_infobboxsegidFr=r type_info_keyrebbox_key seg_pred_keyinstance_id_keyrDrErFrGcs2t||t|_||_||_||_||_dSrS)rHrIr rrrrr)rKr=rrrrrDrLrNrOrIs   zGenerateInstanceTyped.__init__c Cst|}||D]4}||j}||j}||j}||||||\}}|j} | |vr6td| d||d|| <q |S)NzType information with key rl) inst_type type_prob)rTrUrrrrrrm) rKrPrVrXrrr instance_typerrrNrNrOrYs   zGenerateInstanceTyped.__call__)rrrrF)r=rrrerrerrerrerDrErFrG) r[r\r]r^r r_rIrYrbrNrNrLrOr4sr4csTeZdZdZejjejjddddddddd dd d ddfd*fd&d' Zd(d)Z 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_maprcNrdr~rr<rnuclear_prediction_keyrerqinstance_info_keyinstance_map_keyrfrgmask_thresholdrirjrksobel_kernel_sizedistance_smooth_fnr}marker_thresholdr marker_radiusmarker_postprocess_fnwatershed_connectivityrBrrdevicestr | torch.device | NonerFrGcsHtt||||| | | | | |||d |_||_||_||_||_dS)N) rfrrjrrrrrrrrr)rHrIrinstance_map_post_processrrqrr)rKrrqrrrfrrjrrrrrrrrrrLrNrOrIs&  z+HoVerNetInstanceMapPostProcessingd.__init__cCsVt|}|j|jfD] }||vrtdq |||j||j\||j<||j<|S)Nz>The output key ['{k}'] already exists in the input dictionary!)rTrr ValueErrorrrrq)rKrPrVkrNrNrOrYsz+HoVerNetInstanceMapPostProcessingd.__call__)"rrerqrerrerrerfrgrrirjrkrrkrr}rrrrkrr}rrBrrkrrirrrFrG) r[r\r]r^rNPvalueHVrIrYrbrNrNrLrOr7s(!'r7cs@eZdZdZejjdddddddfdfdd 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_maprcNTtype_prediction_keyrerr type_map_keyrfrgrhrireturn_type_maprErrrFrGc s>tt||||d|_||_||_||_||_||_dS)N)rfrhrr) rHrIrtype_post_processrrrrr) rKrrrrrfrhrrrLrNrOrI3s  z+HoVerNetNuclearTypePostProcessingd.__init__cCsXt|}|||j||j||j\||j<}|jr*|j|vr%td|||j<|S)NzNThe output key ['{self.type_map_key}'] already exists in the input dictionary!)rTrrrrrrr)rKrPrVrrNrNrOrYHs  z+HoVerNetNuclearTypePostProcessingd.__call__)rrerrerrerrerfrgrhrirrErrrFrG) r[r\r]r^rNCrrIrYrbrNrNrLrOr:#sr:)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/r0r2r3r5r6r8r9rNrNrNrOsB 4   %3,)$1/*0U3