Skip to content

Commit

Permalink
feat: add border dtype setting for opencv convolution
Browse files Browse the repository at this point in the history
  • Loading branch information
martibosch committed May 26, 2023
1 parent dffc415 commit 11e81c6
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
23 changes: 21 additions & 2 deletions urban_footprinter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,13 @@ class UrbanFootprinter:
"""Urban footprinter."""

def __init__(
self, raster, urban_classes=None, res=None, lulc_dtype=None, mask_dtype=None
self,
raster,
urban_classes=None,
res=None,
convolve_border_type=None,
lulc_dtype=None,
mask_dtype=None,
):
"""Initialize the urban footprinter.
Expand All @@ -36,6 +42,11 @@ def __init__(
res : numeric, optional
Resolution of the `raster` (assumes square pixels). Ignored if `raster` is a
path to a geotiff.
convolve_border_type : int, optional
The type of border to use when convolving the raster with the kernel. Must
be an integer corresponding to an opencv border type. See the opencv docs
for a list of possible values. If not provided, the default value from
`settings.DEFAULT_CONV_BORDER_TYPE` is used.
lulc_dtype : str or numpy dtype, optional
Data type to be used for the LULC array. It may need to be higher than the
raster's original data type to avoid integer overflow when convolving the
Expand All @@ -54,6 +65,9 @@ def __init__(
res = src.res[0] # only square pixels are supported
self.transform = src.transform
self.res = res
if convolve_border_type is None:
convolve_border_type = settings.DEFAULT_CONV_BORDER_TYPE
self.convolve_border_type = convolve_border_type
if lulc_dtype is None:
lulc_dtype = settings.DEFAULT_LULC_DTYPE
self.lulc_dtype = lulc_dtype
Expand Down Expand Up @@ -108,7 +122,12 @@ def get_convolution_result(self, kernel_radius):
kernel[mask] = 1

# urban_mask = ndi.convolve(self.urban_lulc_arr, kernel)
urban_mask = cv2.filter2D(self.urban_lulc_arr, ddepth=-1, kernel=kernel)
urban_mask = cv2.filter2D(
self.urban_lulc_arr,
ddepth=-1,
kernel=kernel,
borderType=cv2.BORDER_REFLECT,
)

# cache the convolution result
self._convolution_result_dict[kernel_radius] = urban_mask
Expand Down
2 changes: 2 additions & 0 deletions urban_footprinter/settings.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Settings."""
import cv2
import numpy as np

DEFAULT_LULC_DTYPE = np.int32
DEFAULT_MASK_DTYPE = np.uint8
DEFAULT_CONV_BORDER_TYPE = cv2.BORDER_REFLECT

0 comments on commit 11e81c6

Please sign in to comment.