Source code for anomalib.post_processing.normalization.cdf
"""Tools for CDF normalization."""# Copyright (C) 2020 Intel Corporation## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions# and limitations under the License.fromtypingimportOptional,Unionimportnumpyasnpimporttorchfromscipy.statsimportnormfromtorchimportTensorfromtorch.distributionsimportNormal
[docs]defstandardize(targets:Union[np.ndarray,Tensor],mean:Union[np.ndarray,Tensor,float],std:Union[np.ndarray,Tensor,float],center_at:Optional[float]=None,)->Union[np.ndarray,Tensor]:"""Standardize the targets to the z-domain."""ifisinstance(targets,np.ndarray):targets=np.log(targets)elifisinstance(targets,Tensor):targets=torch.log(targets)else:raiseValueError(f"Targets must be either Tensor or Numpy array. Received {type(targets)}")standardized=(targets-mean)/stdifcenter_at:standardized-=(center_at-mean)/stdreturnstandardized
[docs]defnormalize(targets:Union[np.ndarray,Tensor],threshold:Union[np.ndarray,Tensor,float])->Union[np.ndarray,Tensor]:"""Normalize the targets by using the cumulative density function."""ifisinstance(targets,Tensor):returnnormalize_torch(targets,threshold)ifisinstance(targets,np.ndarray):returnnormalize_numpy(targets,threshold)raiseValueError(f"Targets must be either Tensor or Numpy array. Received {type(targets)}")
[docs]defnormalize_torch(targets:Tensor,threshold:Tensor)->Tensor:"""Normalize the targets by using the cumulative density function, PyTorch version."""device=targets.deviceimage_threshold=threshold.cpu()dist=Normal(torch.Tensor([0]),torch.Tensor([1]))normalized=dist.cdf(targets.cpu()-image_threshold).to(device)returnnormalized
[docs]defnormalize_numpy(targets:np.ndarray,threshold:Union[np.ndarray,float])->np.ndarray:"""Normalize the targets by using the cumulative density function, Numpy version."""returnnorm.cdf(targets-threshold)