Nic-Ma: Hi @abpwrs ,

Thanks for your quick PR!
hjmjohnson: @abpwrs If one chooses 10%, 90%, min=0, max=200,

The current code seems to pin the 10% value to 0 and 90% value to 200. 

===
The algorithm that we have found works best is
define a linear transformation such that 10% maps to the value 20, and the 90% value mapps to the value 180.  Apply that linear transform for all values in the range (0-200) and set values (after passing through the above linear transform) less than 0 to 0, and greater than 200 to 200.

== Perhaps a flag could distinguish between the two variants of the algorithm that people would expect.

Please provide better documentation, with examples of how the transfer function is computed.







abpwrs: @hjmjohnson I think a flag for this variant sounds great. I'll update this PR accordingly.
diff --git a/docs/source/transforms.rst b/docs/source/transforms.rst
index 8dc3bef9..673d4bae 100644
--- a/docs/source/transforms.rst
+++ b/docs/source/transforms.rst
@@ -187,6 +187,12 @@ Vanilla Transforms
     :members:
     :special-members: __call__
 
+`ScaleIntensityRangePercentiles`
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.. autoclass:: ScaleIntensityRangePercentiles
+    :members:
+    :special-members: __call__
+
 `AdjustContrast`
 ~~~~~~~~~~~~~~~~
 .. autoclass:: AdjustContrast
@@ -503,6 +509,12 @@ Dictionary-based Transforms
     :members:
     :special-members: __call__
 
+`ScaleIntensityRangePercentilesd`
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.. autoclass:: ScaleIntensityRangePercentilesd
+    :members:
+    :special-members: __call__
+
 `AdjustContrastd`
 ~~~~~~~~~~~~~~~~~
 .. autoclass:: AdjustContrastd
diff --git a/monai/transforms/intensity/array.py b/monai/transforms/intensity/array.py
index 06dcfcfa..0851b121 100644
--- a/monai/transforms/intensity/array.py
+++ b/monai/transforms/intensity/array.py
@@ -14,6 +14,7 @@ https://github.com/Project-MONAI/MONAI/wiki/MONAI_Design
 """
 
 from typing import Optional, Tuple
+from warnings import warn
 
 import numpy as np
 
@@ -236,6 +237,10 @@ class ScaleIntensityRange(Transform):
         self.clip = clip
 
     def __call__(self, img):
+        if self.a_max - self.a_min == 0.0:
+            warn("Divide by zero (a_min == a_max)", Warning)
+            return img - self.a_min + self.b_min
+
         img = (img - self.a_min) / (self.a_max - self.a_min)
         img = img * (self.b_max - self.b_min) + self.b_min
         if self.clip:
@@ -297,3 +302,89 @@ class RandAdjustContrast(Randomizable, Transform):
             return img
         adjuster = AdjustContrast(self.gamma_value)
         return adjuster(img)
+
+
+class ScaleIntensityRangePercentiles(Transform):
+    """
+    Apply range scaling to a numpy array based on the intensity distribution of the input.
+
+    By default this transform will scale from [lower_intensity_percentile, upper_intensity_percentile] to [b_min, b_max], where 
+    {lower,upper}_intensity_percentile are the intensity values at the corresponding percentiles of ``img``. 
+
+    The ``relative`` parameter can also be set to scale from [lower_intensity_percentile, upper_intensity_percentile] to the 
+    lower and upper percentiles of the output range [b_min, b_max]
+
+    For example:
+
+    .. code-block:: python
+        :emphasize-lines: 11, 22
+
+        image = np.array(
+            [[[1, 2, 3, 4, 5],
+              [1, 2, 3, 4, 5],
+              [1, 2, 3, 4, 5],
+              [1, 2, 3, 4, 5],
+              [1, 2, 3, 4, 5],
+              [1, 2, 3, 4, 5]]]) 
+
+        # Scale from lower and upper image intensity percentiles 
+        # to output range [b_min, b_max]
+        scaler = ScaleIntensityRangePercentiles(10, 90, 0, 200, False, False)
+        print(scaler(image))
+        [[[0., 50., 100., 150., 200.],
+          [0., 50., 100., 150., 200.],
+          [0., 50., 100., 150., 200.],
+          [0., 50., 100., 150., 200.],
+          [0., 50., 100., 150., 200.],
+          [0., 50., 100., 150., 200.]]]
+
+        # Scale from lower and upper image intensity percentiles 
+        # to lower and upper percentiles of the output range [b_min, b_max]
+        rel_scaler = ScaleIntensityRangePercentiles(10, 90, 0, 200, False, True)
+        print(rel_scaler(image))
+        [[[20., 60., 100., 140., 180.],
+          [20., 60., 100., 140., 180.],
+          [20., 60., 100., 140., 180.],
+          [20., 60., 100., 140., 180.],
+          [20., 60., 100., 140., 180.],
+          [20., 60., 100., 140., 180.]]]
+
+
+    Args:
+        lower: lower intensity percentile.
+        upper: upper intensity percentile.
+        b_min: intensity target range min.
+        b_max: intensity target range max.
+        clip: whether to perform clip after scaling.
+        relative: whether to scale to the coresponding percentiles of [b_min, b_max].
+    """
+
+    def __init__(
+        self, lower: float, upper: float, b_min: float, b_max: float, clip: bool = False, relative: bool = False
+    ) -> None:
+        assert 0.0 <= lower <= 100.0, "Percentiles must be in the range [0, 100]"
+        assert 0.0 <= upper <= 100.0, "Percentiles must be in the range [0, 100]"
+        self.lower = lower
+        self.upper = upper
+        self.b_min = b_min
+        self.b_max = b_max
+        self.clip = clip
+        self.relative = relative
+
+    def __call__(self, img):
+        a_min = np.percentile(img, self.lower)
+        a_max = np.percentile(img, self.upper)
+        b_min = self.b_min
+        b_max = self.b_max
+
+        if self.relative:
+            b_min = ((self.b_max - self.b_min) * (self.lower / 100.0)) + self.b_min
+            b_max = ((self.b_max - self.b_min) * (self.upper / 100.0)) + self.b_min
+
+        scalar = ScaleIntensityRange(a_min=a_min, a_max=a_max, b_min=b_min, b_max=b_max, clip=False)
+        img = scalar(img)
+
+        if self.clip:
+            img = np.clip(img, self.b_min, self.b_max)
+
+        return img
diff --git a/monai/transforms/intensity/dictionary.py b/monai/transforms/intensity/dictionary.py
index ea73410e..494e304a 100644
--- a/monai/transforms/intensity/dictionary.py
+++ b/monai/transforms/intensity/dictionary.py
@@ -28,6 +28,7 @@ from monai.transforms.intensity.array import (
     AdjustContrast,
     ShiftIntensity,
     ScaleIntensity,
+    ScaleIntensityRangePercentiles,
 )
 
 
@@ -343,6 +344,41 @@ class RandAdjustContrastd(Randomizable, MapTransform):
         return d
 
 
+class ScaleIntensityRangePercentilesd(MapTransform):
+    """
+    Dictionary-based wrapper of :py:class:`monai.transforms.ScaleIntensityRangePercentiles`.
+
+    Args:
+        keys: keys of the corresponding items to be transformed.
+            See also: monai.transforms.MapTransform
+        lower: lower percentile.
+        upper: upper percentile.
+        b_min: intensity target range min.
+        b_max: intensity target range max.
+        clip: whether to perform clip after scaling.
+        relative: whether to scale to the coresponding percentiles of [b_min, b_max]
+    """
+
+    def __init__(
+        self,
+        keys: KeysCollection,
+        lower: float,
+        upper: float,
+        b_min: float,
+        b_max: float,
+        clip: bool = False,
+        relative: bool = False,
+    ) -> None:
+        super().__init__(keys)
+        self.scaler = ScaleIntensityRangePercentiles(lower, upper, b_min, b_max, clip, relative)
+
+    def __call__(self, data):
+        d = dict(data)
+        for key in self.keys:
+            d[key] = self.scaler(d[key])
+        return d
+
+
 RandGaussianNoiseD = RandGaussianNoiseDict = RandGaussianNoised
 ShiftIntensityD = ShiftIntensityDict = ShiftIntensityd
 RandShiftIntensityD = RandShiftIntensityDict = RandShiftIntensityd
@@ -353,3 +389,4 @@ ThresholdIntensityD = ThresholdIntensityDict = ThresholdIntensityd
 ScaleIntensityRangeD = ScaleIntensityRangeDict = ScaleIntensityRanged
 AdjustContrastD = AdjustContrastDict = AdjustContrastd
 RandAdjustContrastD = RandAdjustContrastDict = RandAdjustContrastd
+ScaleIntensityRangePercentilesD = ScaleIntensityRangePercentilesDict = ScaleIntensityRangePercentilesd

Add percentile version of ScaleIntensityRange
**Describe the solution you'd like**

A variant of `monai.transforms.ScaleIntensityRange` that has upper and lower intensity percentile parameters instead of `a_min` and `a_max`.      

So this transform would rescale each image differently depending on the intensity distribution of the `img` parameter instead of scaling all images the same, as `ScaleIntensityRange` does.



General idea:
```python
class ScaleIntensityRangePercentiles(Transform):
    def __init__(self, lower_percentile: float, upper_percentile: float, b_min: float, b_max: float, clip: bool = False) -> None:
        self.lower_percentile = lower_percentile
        self.upper_percentile = upper_percentile
        self.b_min = b_min
        self.b_max = b_max
        self.clip = clip

    def __call__(self, img):
        ### Calculate percentiles from img
        ### Rescale using percentiles
        ### Optional clipping
```
**Describe alternatives you've considered**
Modify the current `ScaleIntensityRange` transform to include a percentile option:         

`ScaleIntensityRange(a_min, a_max, b_min, b_max, clip=False, percentile=True)`         

Which would treat `a_min` and `a_max` as percentiles instead of intensity values.


diff --git a/tests/test_scale_intensity_range_percentiles.py b/tests/test_scale_intensity_range_percentiles.py
new file mode 100644
index 00000000..ace11fcc
--- /dev/null
+++ b/tests/test_scale_intensity_range_percentiles.py
@@ -0,0 +1,60 @@
+# Copyright 2020 MONAI Consortium
+# 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.
+
+import unittest
+
+import numpy as np
+
+from monai.transforms.intensity.array import ScaleIntensityRangePercentiles
+from tests.utils import NumpyImageTestCase2D
+
+
+class TestScaleIntensityRangePercentiles(NumpyImageTestCase2D):
+    def test_scaling(self):
+        img = self.imt
+        lower = 10
+        upper = 99
+        b_min = 0
+        b_max = 255
+
+        a_min = np.percentile(img, lower)
+        a_max = np.percentile(img, upper)
+        expected = (img - a_min) / (a_max - a_min)
+        expected = (expected * (b_max - b_min)) + b_min
+        scaler = ScaleIntensityRangePercentiles(lower=lower, upper=upper, b_min=b_min, b_max=b_max)
+        self.assertTrue(np.allclose(expected, scaler(img)))
+
+    def test_relative_scaling(self):
+        img = self.imt
+        lower = 10
+        upper = 99
+        b_min = 100
+        b_max = 300
+        scaler = ScaleIntensityRangePercentiles(lower=lower, upper=upper, b_min=b_min, b_max=b_max, relative=True)
+
+        expected_a_min = np.percentile(img, lower)
+        expected_a_max = np.percentile(img, upper)
+        expected_b_min = ((b_max - b_min) * (lower / 100.0)) + b_min
+        expected_b_max = ((b_max - b_min) * (upper / 100.0)) + b_min
+        expected_img = (img - expected_a_min) / (expected_a_max - expected_a_min)
+        expected_img = (expected_img * (expected_b_max - expected_b_min)) + expected_b_min
+
+        self.assertTrue(np.allclose(expected_img, scaler(img)))
+
+    def test_invalid_instantiation(self):
+        self.assertRaises(AssertionError, ScaleIntensityRangePercentiles, lower=-10, upper=99, b_min=0, b_max=255)
+        self.assertRaises(AssertionError, ScaleIntensityRangePercentiles, lower=101, upper=99, b_min=0, b_max=255)
+        self.assertRaises(AssertionError, ScaleIntensityRangePercentiles, lower=30, upper=-20, b_min=0, b_max=255)
+        self.assertRaises(AssertionError, ScaleIntensityRangePercentiles, lower=30, upper=900, b_min=0, b_max=255)
+
+
+if __name__ == "__main__":
+    unittest.main()
diff --git a/tests/test_scale_intensity_range_percentilesd.py b/tests/test_scale_intensity_range_percentilesd.py
new file mode 100644
index 00000000..75e79b7c
--- /dev/null
+++ b/tests/test_scale_intensity_range_percentilesd.py
@@ -0,0 +1,76 @@
+# Copyright 2020 MONAI Consortium
+# 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.
+
+import unittest
+
+import numpy as np
+
+from monai.transforms.intensity.dictionary import ScaleIntensityRangePercentilesd
+from tests.utils import NumpyImageTestCase2D
+
+
+class TestScaleIntensityRangePercentilesd(NumpyImageTestCase2D):
+    def test_scaling(self):
+        img = self.imt
+        data = dict()
+        data["img"] = img
+        lower = 10
+        upper = 99
+        b_min = 0
+        b_max = 255
+
+        a_min = np.percentile(img, lower)
+        a_max = np.percentile(img, upper)
+        expected = (img - a_min) / (a_max - a_min)
+        expected = (expected * (b_max - b_min)) + b_min
+
+        scaler = ScaleIntensityRangePercentilesd(keys=data.keys(), lower=lower, upper=upper, b_min=b_min, b_max=b_max)
+
+        self.assertTrue(np.allclose(expected, scaler(data)["img"]))
+
+    def test_relative_scaling(self):
+        img = self.imt
+        data = dict()
+        data["img"] = img
+        lower = 10
+        upper = 99
+        b_min = 100
+        b_max = 300
+        scaler = ScaleIntensityRangePercentilesd(
+            keys=data.keys(), lower=lower, upper=upper, b_min=b_min, b_max=b_max, relative=True
+        )
+
+        expected_a_min = np.percentile(img, lower)
+        expected_a_max = np.percentile(img, upper)
+        expected_b_min = ((b_max - b_min) * (lower / 100.0)) + b_min
+        expected_b_max = ((b_max - b_min) * (upper / 100.0)) + b_min
+        expected_img = (img - expected_a_min) / (expected_a_max - expected_a_min)
+        expected_img = (expected_img * (expected_b_max - expected_b_min)) + expected_b_min
+
+        self.assertTrue(np.allclose(expected_img, scaler(data)["img"]))
+
+    def test_invalid_instantiation(self):
+        self.assertRaises(
+            AssertionError, ScaleIntensityRangePercentilesd, keys=["img"], lower=-1, upper=99, b_min=0, b_max=255
+        )
+        self.assertRaises(
+            AssertionError, ScaleIntensityRangePercentilesd, keys=["img"], lower=101, upper=99, b_min=0, b_max=255
+        )
+        self.assertRaises(
+            AssertionError, ScaleIntensityRangePercentilesd, keys=["img"], lower=30, upper=-2, b_min=0, b_max=255
+        )
+        self.assertRaises(
+            AssertionError, ScaleIntensityRangePercentilesd, keys=["img"], lower=30, upper=1000, b_min=0, b_max=255
+        )
+
+
+if __name__ == "__main__":
+    unittest.main()

pip install -e .[all]
parse_log_pytest
requirements.txt
pytest black flake8 mypy pytype
apt-get update apt-get install -y gcc
3.6
requirements.txt
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
absl-py==1.4.0
attrs==22.2.0
black==22.8.0
cachetools==4.2.4
certifi==2021.5.30
charset-normalizer==2.0.12
click==8.0.4
cycler==0.11.0
dataclasses==0.8
decorator==4.4.2
flake8==5.0.4
google-auth==2.22.0
google-auth-oauthlib==0.4.6
grpcio==1.48.2
idna==3.10
imageio==2.15.0
importlab==0.8.1
importlib-metadata==4.8.3
iniconfig==1.1.1
kiwisolver==1.3.1
libcst==0.4.1
Markdown==3.3.7
matplotlib==3.3.4
mccabe==0.7.0
-e git+https://github.com/Project-MONAI/MONAI.git@d25e4e56ef9c5e56fefbce0478b61e1f2a114c9f#egg=monai
mypy==0.971
mypy-extensions==1.0.0
networkx==2.5.1
nibabel==3.2.2
ninja==1.11.1.1
numpy==1.19.5
oauthlib==3.2.2
packaging==21.3
pathspec==0.9.0
Pillow==8.4.0
platformdirs==2.4.0
pluggy==1.0.0
protobuf==3.19.6
py==1.11.0
pyasn1==0.5.1
pyasn1-modules==0.3.0
pycodestyle==2.9.1
pyflakes==2.5.0
pyparsing==3.1.4
pytest==7.0.1
python-dateutil==2.9.0.post0
pytorch-ignite==0.3.0
pytype==2022.1.5
PyWavelets==1.1.1
PyYAML==6.0.1
requests==2.27.1
requests-oauthlib==2.0.0
rsa==4.9
scikit-image==0.17.2
scipy==1.5.4
six==1.17.0
tabulate==0.8.10
tensorboard==2.10.1
tensorboard-data-server==0.6.1
tensorboard-plugin-wit==1.8.1
tifffile==2020.9.3
toml==0.10.2
tomli==1.2.3
torch==1.10.2
typed-ast==1.5.5
typing-inspect==0.9.0
typing_extensions==4.1.1
urllib3==1.26.20
Werkzeug==2.0.3
zipp==3.6.0

name: MONAI
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - ca-certificates=2025.2.25=h06a4308_0
  - certifi=2021.5.30=py36h06a4308_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.3=he6710b0_2
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - ncurses=6.4=h6a678d5_0
  - openssl=1.1.1w=h7f8727e_0
  - pip=21.2.2=py36h06a4308_0
  - python=3.6.13=h12debd9_1
  - readline=8.2=h5eee18b_0
  - setuptools=58.0.4=py36h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - wheel=0.37.1=pyhd3eb1b0_0
  - xz=5.6.4=h5eee18b_1
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - absl-py==1.4.0
      - attrs==22.2.0
      - black==22.8.0
      - cachetools==4.2.4
      - charset-normalizer==2.0.12
      - click==8.0.4
      - cycler==0.11.0
      - dataclasses==0.8
      - decorator==4.4.2
      - flake8==5.0.4
      - google-auth==2.22.0
      - google-auth-oauthlib==0.4.6
      - grpcio==1.48.2
      - idna==3.10
      - imageio==2.15.0
      - importlab==0.8.1
      - importlib-metadata==4.8.3
      - iniconfig==1.1.1
      - kiwisolver==1.3.1
      - libcst==0.4.1
      - markdown==3.3.7
      - matplotlib==3.3.4
      - mccabe==0.7.0
      - mypy==0.971
      - mypy-extensions==1.0.0
      - networkx==2.5.1
      - nibabel==3.2.2
      - ninja==1.11.1.1
      - numpy==1.19.5
      - oauthlib==3.2.2
      - packaging==21.3
      - pathspec==0.9.0
      - pillow==8.4.0
      - platformdirs==2.4.0
      - pluggy==1.0.0
      - protobuf==3.19.6
      - py==1.11.0
      - pyasn1==0.5.1
      - pyasn1-modules==0.3.0
      - pycodestyle==2.9.1
      - pyflakes==2.5.0
      - pyparsing==3.1.4
      - pytest==7.0.1
      - python-dateutil==2.9.0.post0
      - pytorch-ignite==0.3.0
      - pytype==2022.1.5
      - pywavelets==1.1.1
      - pyyaml==6.0.1
      - requests==2.27.1
      - requests-oauthlib==2.0.0
      - rsa==4.9
      - scikit-image==0.17.2
      - scipy==1.5.4
      - six==1.17.0
      - tabulate==0.8.10
      - tensorboard==2.10.1
      - tensorboard-data-server==0.6.1
      - tensorboard-plugin-wit==1.8.1
      - tifffile==2020.9.3
      - toml==0.10.2
      - tomli==1.2.3
      - torch==1.10.2
      - typed-ast==1.5.5
      - typing-extensions==4.1.1
      - typing-inspect==0.9.0
      - urllib3==1.26.20
      - werkzeug==2.0.3
      - zipp==3.6.0
prefix: /opt/conda/envs/MONAI

tests/test_scale_intensity_range_percentiles.py::TestScaleIntensityRangePercentiles::test_invalid_instantiation tests/test_scale_intensity_range_percentiles.py::TestScaleIntensityRangePercentiles::test_relative_scaling tests/test_scale_intensity_range_percentiles.py::TestScaleIntensityRangePercentiles::test_scaling tests/test_scale_intensity_range_percentilesd.py::TestScaleIntensityRangePercentilesd::test_invalid_instantiation tests/test_scale_intensity_range_percentilesd.py::TestScaleIntensityRangePercentilesd::test_relative_scaling tests/test_scale_intensity_range_percentilesd.py::TestScaleIntensityRangePercentilesd::test_scaling
monai/transforms/intensity/array.py monai/transforms/intensity/dictionary.py docs/source/transforms.rst
monai/transforms/intensity/array.py monai/transforms/intensity/dictionary.py docs/source/transforms.rst