def test_normalize(self): img = np.arange(0, 9).reshape(3, 3) value_range_in = (0, 10) value_range_out = (0, 1) expected = np.array([[0, .1, .2], [.3, .4, .5], [.6, .7, .8]]) calculated = ImageTools.normalize(img, value_range_in=value_range_in, value_range_out=value_range_out) np.testing.assert_array_almost_equal(expected, calculated)
def test_normalize_0to255(self): img = np.arange(-4, 5).reshape(3, 3) / 5 value_range_in = (-1, 1) value_range_out = (0, 255) expected = np.array([[25.5, 51., 76.5], [102., 127.5, 153.], [178.5, 204., 229.5]]) calculated = ImageTools.normalize(img, value_range_in=value_range_in, value_range_out=value_range_out) np.testing.assert_array_almost_equal(expected, calculated)
def test_normalize_clip(self): img = np.arange(0, 9).reshape(3, 3) value_range_in = (0, 5) value_range_out = (0, 1) expected = np.array([[0, .2, .4], [.6, .8, 1], [1, 1, 1]]) calculated = ImageTools.normalize(img, value_range_in=value_range_in, value_range_out=value_range_out, clip=True) np.testing.assert_array_almost_equal(expected, calculated)
def get_ndvi(red, nir, vrange=(-1, 1), dtype=np.float32): """ Calculate the NDVI (Normalized-Difference Vegetation Index) :param red: The red band dataset :type red: :class:`Common.GDalDatasetWrapper.GDalDatasetWrapper` :param nir: The nir band dataset :type nir: :class:`Common.GDalDatasetWrapper.GDalDatasetWrapper` :param vrange: The range of output values as tuple. By default: (-1, 1). :type vrange: tuple of int :param dtype: The output dtype. :type dtype: :class`np.dtype` :return: The NDVI as numpy array. :rtype: :class:`Common.GDalDatasetWrapper.GDalDatasetWrapper` """ if nir.extent != red.extent or nir.epsg != red.epsg: raise ValueError("Cannot calculate NDSI on two different extents.") if nir.resolution != red.resolution: # Resize to nir resolution in this case. tr = " ".join([str(i) for i in nir.resolution]) ds_red = ImageTools.gdal_translate(red, tr=tr, r="cubic") else: ds_red = red # TODO Add new test img_red = np.array(ds_red.array, dtype=np.float32) img_nir = np.array(nir.array, dtype=np.float32) # Compensate for nan: np.seterr(divide='ignore', invalid='ignore') img_ndvi = np.where((img_red + img_nir) != 0, (img_red - img_nir) / (img_red + img_nir), -1) # Scale to vrange img_ndvi_scaled = ImageTools.normalize(img_ndvi, value_range_out=vrange, value_range_in=(-1, 1), dtype=dtype, clip=True) return GDalDatasetWrapper(ds=nir.get_ds(), array=img_ndvi_scaled)