Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not apply linear stretch to alpha band #145

Merged
merged 1 commit into from
Sep 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
36 changes: 36 additions & 0 deletions trollimage/tests/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -1541,6 +1541,42 @@ def test_linear_stretch(self):

np.testing.assert_allclose(img.data.values, res, atol=1.e-6)

def test_linear_stretch_does_not_affect_alpha(self):
"""Test linear stretching with cutoffs."""
arr = np.arange(100).reshape(5, 5, 4) / 74.
arr[:, :, -1] = 1 # alpha channel, fully opaque
data = xr.DataArray(arr.copy(), dims=['y', 'x', 'bands'],
coords={'bands': ['R', 'G', 'B', 'A']})
img = xrimage.XRImage(data)
img.stretch_linear((0.005, 0.005))
res = np.array([[[-0.005051, -0.005051, -0.005051, 1.],
[0.037037, 0.037037, 0.037037, 1.],
[0.079125, 0.079125, 0.079125, 1.],
[0.121212, 0.121212, 0.121212, 1.],
[0.1633, 0.1633, 0.1633, 1.]],
[[0.205387, 0.205387, 0.205387, 1.],
[0.247475, 0.247475, 0.247475, 1.],
[0.289562, 0.289562, 0.289562, 1.],
[0.33165, 0.33165, 0.33165, 1.],
[0.373737, 0.373737, 0.373737, 1.]],
[[0.415825, 0.415825, 0.415825, 1.],
[0.457912, 0.457912, 0.457912, 1.],
[0.5, 0.5, 0.5, 1.],
[0.542088, 0.542088, 0.542088, 1.],
[0.584175, 0.584175, 0.584175, 1.]],
[[0.626263, 0.626263, 0.626263, 1.],
[0.66835, 0.66835, 0.66835, 1.],
[0.710438, 0.710438, 0.710438, 1.],
[0.752525, 0.752525, 0.752525, 1.],
[0.794613, 0.794613, 0.794613, 1.]],
[[0.8367, 0.8367, 0.8367, 1.],
[0.878788, 0.878788, 0.878788, 1.],
[0.920875, 0.920875, 0.920875, 1.],
[0.962963, 0.962963, 0.962963, 1.],
[1.005051, 1.005051, 1.005051, 1.]]])

np.testing.assert_allclose(img.data.values, res, atol=1.e-6)

def test_histogram_stretch(self):
"""Test histogram stretching."""
arr = np.arange(75).reshape(5, 5, 3) / 74.
Expand Down
38 changes: 27 additions & 11 deletions trollimage/xrimage.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ def rio_save(self, filename, fformat=None, fill_value=None,
warnings.warn(
"include_scale_offset_tags is deprecated, please use "
"scale_offset_tags to indicate tag labels",
DeprecationWarning)
DeprecationWarning, stacklevel=2)
scale_offset_tags = scale_offset_tags or ("scale", "offset")

if tags is None:
Expand Down Expand Up @@ -659,7 +659,7 @@ def _get_dtype_scale_offset(self, dtype, fill_value):
"Specified fill value will overlap with valid "
"data. To avoid this warning specify a fill_value "
"that is the minimum or maximum for the data type "
"being saved to.")
"being saved to.", stacklevel=3)
return scale, offset

def _scale_to_dtype(self, data, dtype, fill_value=None):
Expand Down Expand Up @@ -1019,29 +1019,45 @@ def stretch_linear(self, cutoffs=(0.005, 0.005)):
"""
logger.debug("Perform a linear contrast stretch.")

left, right = self._get_left_and_right_quantiles_for_linear_stretch(cutoffs)

self.crude_stretch(left, right)

def _get_left_and_right_quantiles_for_linear_stretch(self, cutoffs):
logger.debug("Calculate the histogram quantiles: ")
logger.debug("Left and right quantiles: " +
str(cutoffs[0]) + " " + str(cutoffs[1]))

cutoff_type = np.float64
# numpy percentile (which quantile calls) returns 64-bit floats
# unless the value is a higher order float
if np.issubdtype(self.data.dtype, np.floating) and \
np.dtype(self.data.dtype).itemsize > 8:
cutoff_type = self.data.dtype
left, right = dask.delayed(self._compute_quantile, nout=2)(self.data.data, self.data.dims, cutoffs)
left_data = da.from_delayed(left,
shape=(self.data.sizes['bands'],),
dtype=cutoff_type)

data = self.data
if 'A' in self.data.coords['bands'].values:
data = self.data.sel(bands=self.data.coords['bands'].values[:-1])

left_data, right_data = self._get_left_and_right_quantiles_without_alpha(data, cutoffs, cutoff_type)

if 'A' in self.data.coords['bands'].values:
left_data = np.hstack([left_data, np.array([0])])
right_data = np.hstack([right_data, np.array([1])])
left = xr.DataArray(left_data, dims=('bands',),
coords={'bands': self.data['bands']})
right_data = da.from_delayed(right,
shape=(self.data.sizes['bands'],),
dtype=cutoff_type)
right = xr.DataArray(right_data, dims=('bands',),
coords={'bands': self.data['bands']})
return left, right

self.crude_stretch(left, right)
def _get_left_and_right_quantiles_without_alpha(self, data, cutoffs, cutoff_type):
left, right = dask.delayed(self._compute_quantile, nout=2)(data.data, data.dims, cutoffs)
left_data = da.from_delayed(left,
shape=(data.sizes['bands'],),
dtype=cutoff_type)
right_data = da.from_delayed(right,
shape=(data.sizes['bands'],),
dtype=cutoff_type)
return left_data, right_data

def crude_stretch(self, min_stretch=None, max_stretch=None):
"""Perform simple linear stretching.
Expand Down