Skip to content

Segmentation API

obia.segmentation.segment

obia.segmentation.segment

Segments

Segments class for handling and processing image segments.

Attributes:

Name Type Description
_segments

Internal representation of segments data.

segments

Public representation of segments data.

method

Method used for segmentation.

params

Additional parameters for segmentation.

Methods:

Name Description
__init__

Initializes the Segments object with segments data, a method, and additional parameters.

to_segmented_image

Converts a given PIL Image to a segmented image with boundaries overlaid.

write_segments

Writes the segments data to a file.

Source code in obia/segmentation/segment.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Segments:
    """
    Segments class for handling and processing image segments.

    Attributes:
        _segments: Internal representation of segments data.
        segments: Public representation of segments data.
        method: Method used for segmentation.
        params: Additional parameters for segmentation.

    Methods:
        __init__(_segments, segments, method, **kwargs):
            Initializes the Segments object with segments data, a method, and additional parameters.

        to_segmented_image(image):
            Converts a given PIL Image to a segmented image with boundaries overlaid.

        write_segments(file_path):
            Writes the segments data to a file.
    """
    _segments = None
    segments = None
    method = None
    params = {}

    def __init__(self, _segments, segments, method, **kwargs):
        self._segments = _segments
        self.segments = segments
        self.method = method
        self.params.update(kwargs)

    def to_segmented_image(self, image):
        """
        :param image: An input image expected to be of type PIL Image.
        :return: A new image with the boundaries marked on the segments.
        """
        if not isinstance(image, PILImage):
            raise TypeError('Input must be a PIL Image')
        img = np.array(image)
        boundaries = mark_boundaries(img, self._segments)
        boundaries_int = boundaries * 255

        masked_img = boundaries_int.copy()
        return fromarray(masked_img.astype(np.uint8))

    def write_segments(self, file_path):
        """
        :param file_path: The path to the file where segments will be written.
        :return: None
        """
        self.segments.to_file(file_path)

to_segmented_image(image)

:param image: An input image expected to be of type PIL Image. :return: A new image with the boundaries marked on the segments.

Source code in obia/segmentation/segment.py
41
42
43
44
45
46
47
48
49
50
51
52
53
def to_segmented_image(self, image):
    """
    :param image: An input image expected to be of type PIL Image.
    :return: A new image with the boundaries marked on the segments.
    """
    if not isinstance(image, PILImage):
        raise TypeError('Input must be a PIL Image')
    img = np.array(image)
    boundaries = mark_boundaries(img, self._segments)
    boundaries_int = boundaries * 255

    masked_img = boundaries_int.copy()
    return fromarray(masked_img.astype(np.uint8))

write_segments(file_path)

:param file_path: The path to the file where segments will be written. :return: None

Source code in obia/segmentation/segment.py
55
56
57
58
59
60
def write_segments(self, file_path):
    """
    :param file_path: The path to the file where segments will be written.
    :return: None
    """
    self.segments.to_file(file_path)

segment(image, segmentation_bands=None, statistics_bands=None, method='slic', calc_mean=True, calc_variance=True, calc_skewness=True, calc_kurtosis=True, calc_contrast=True, calc_dissimilarity=True, calc_homogeneity=True, calc_ASM=True, calc_energy=True, calc_correlation=True, **kwargs)

:param image: Input image for segmentation and feature extraction. :param segmentation_bands: Bands to be used for segmentation. Default is None. :param statistics_bands: Bands to be used for statistical calculations. Default is None. :param method: Segmentation method to be used. Default is "slic". :param calc_mean: Flag to calculate mean of segments. Default is True. :param calc_variance: Flag to calculate variance of segments. Default is True. :param calc_skewness: Flag to calculate skewness of segments. Default is True. :param calc_kurtosis: Flag to calculate kurtosis of segments. Default is True. :param calc_contrast: Flag to calculate contrast of segments. Default is True. :param calc_dissimilarity: Flag to calculate dissimilarity of segments. Default is True. :param calc_homogeneity: Flag to calculate homogeneity of segments. Default is True. :param calc_ASM: Flag to calculate angular second moment of segments. Default is True. :param calc_energy: Flag to calculate energy of segments. Default is True. :param calc_correlation: Flag to calculate correlation of segments. Default is True. :param kwargs: Additional parameters for segmentation and feature extraction. :return: Segments object containing the segmented image and statistics.

Source code in obia/segmentation/segment.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
def segment(image, segmentation_bands=None, statistics_bands=None,
            method="slic", calc_mean=True, calc_variance=True,
            calc_skewness=True, calc_kurtosis=True, calc_contrast=True,
            calc_dissimilarity=True, calc_homogeneity=True, calc_ASM=True,
            calc_energy=True, calc_correlation=True, **kwargs):
    """
    :param image: Input image for segmentation and feature extraction.
    :param segmentation_bands: Bands to be used for segmentation. Default is None.
    :param statistics_bands: Bands to be used for statistical calculations. Default is None.
    :param method: Segmentation method to be used. Default is "slic".
    :param calc_mean: Flag to calculate mean of segments. Default is True.
    :param calc_variance: Flag to calculate variance of segments. Default is True.
    :param calc_skewness: Flag to calculate skewness of segments. Default is True.
    :param calc_kurtosis: Flag to calculate kurtosis of segments. Default is True.
    :param calc_contrast: Flag to calculate contrast of segments. Default is True.
    :param calc_dissimilarity: Flag to calculate dissimilarity of segments. Default is True.
    :param calc_homogeneity: Flag to calculate homogeneity of segments. Default is True.
    :param calc_ASM: Flag to calculate angular second moment of segments. Default is True.
    :param calc_energy: Flag to calculate energy of segments. Default is True.
    :param calc_correlation: Flag to calculate correlation of segments. Default is True.
    :param kwargs: Additional parameters for segmentation and feature extraction.
    :return: Segments object containing the segmented image and statistics.
    """
    segments_gdf = create_segments(image, segmentation_bands=segmentation_bands, method=method, **kwargs)
    objects_gdf = create_objects(segments_gdf, image, spectral_bands=statistics_bands, calc_mean=calc_mean,
                                 calc_variance=calc_variance, calc_skewness=calc_skewness, calc_kurtosis=calc_kurtosis,
                                 calc_contrast=calc_contrast, calc_dissimilarity=calc_dissimilarity,
                                 calc_homogeneity=calc_homogeneity, calc_ASM=calc_ASM, calc_energy=calc_energy,
                                 calc_correlation=calc_correlation)

    return Segments(segments_gdf, objects_gdf, method, **kwargs)

obia.segmentation.segment_boundaries

obia.segmentation.segment_boundaries

create_segments(image, segmentation_bands=None, method='slic', **kwargs)

:param image: The image to segment, composed of multiple bands. :type image: Image object :param segmentation_bands: List of band indices to use for segmentation. If None, all bands are used. :type segmentation_bands: list[int] or None :param method: Segmentation method to use: 'slic' or 'quickshift'. :type method: str :param kwargs: Additional keyword arguments passed to the segmentation algorithm. :type kwargs: dict :return: GeoDataFrame containing segmented geometries, with a column for segment IDs. :rtype: GeoDataFrame

Source code in obia/segmentation/segment_boundaries.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def create_segments(image, segmentation_bands=None, method="slic", **kwargs):
    """
    :param image: The image to segment, composed of multiple bands.
    :type image: Image object
    :param segmentation_bands: List of band indices to use for segmentation. If None, all bands are used.
    :type segmentation_bands: list[int] or None
    :param method: Segmentation method to use: 'slic' or 'quickshift'.
    :type method: str
    :param kwargs: Additional keyword arguments passed to the segmentation algorithm.
    :type kwargs: dict
    :return: GeoDataFrame containing segmented geometries, with a column for segment IDs.
    :rtype: GeoDataFrame
    """
    num_bands = image.img_data.shape[2]
    for i in range(image.img_data.shape[2]):
        image.img_data[:, :, i] = normalize_band(image.img_data[:, :, i])
    # Use all bands if segmentation_bands is None
    if segmentation_bands is None:
        segmentation_bands = list(range(num_bands))

    for band in segmentation_bands:
        if band >= num_bands or band < 0:
            raise IndexError(f"Band index {band} out of range. Available bands indices: 0 to {num_bands - 1}.")

    # Prepare the image data for segmentation
    img_to_segment = img_as_float(image.img_data[:, :, segmentation_bands])

    # Check shape of img_to_segment before passing to slic
    print("Shape of img_to_segment:", img_to_segment.shape)

    if method == 'quickshift':
        segments = quickshift(img_to_segment, **kwargs)
    elif method == 'slic':
        segments = slic(img_to_segment, **kwargs)  # Ensure no channel_axis or conflicting arguments
    else:
        raise Exception('An unknown segmentation method was requested.')

    mask = kwargs.get('mask', None)
    if mask is not None:
        segments[mask == 0] = -1

    segment_ids = np.unique(segments)

    geometries = []
    for segment_id in segment_ids:
        if segment_id == -1:
            continue
        segment_mask = segments == segment_id
        for s, v in shapes(segment_mask.astype('int32')):
            if v == 1:
                geometry = shape(s)
                transformed_geom = affine_transform(geometry, image.affine_transformation)
                geometries.append(transformed_geom)

    gdf = GeoDataFrame(geometry=geometries)

    srs = pyproj.CRS(image.crs)
    srs_epsg = srs.to_epsg()
    gdf.crs = f"EPSG:{srs_epsg}"
    gdf['segment_id'] = range(1, len(gdf) + 1)
    return gdf

normalize_band(band)

:param band: The input band array that needs to be normalized. This should be a numpy array of numeric values. :return: A numpy array with the normalized values, where the minimum value is mapped to 0 and the maximum value is mapped to 1.

Source code in obia/segmentation/segment_boundaries.py
11
12
13
14
15
16
def normalize_band(band):
    """
    :param band: The input band array that needs to be normalized. This should be a numpy array of numeric values.
    :return: A numpy array with the normalized values, where the minimum value is mapped to 0 and the maximum value is mapped to 1.
    """
    return (band - np.min(band)) / (np.max(band) - np.min(band))

obia.segmentation.segment_statistics

obia.segmentation.segment_statistics

calculate_spectral_stats(image, statistics_bands, calc_mean=True, calc_variance=True, calc_min=True, calc_max=True, calc_skewness=True, calc_kurtosis=True)

Calculates a range of statistical measures for specific bands of a spectral image. The statistics calculated are mean, variance, minimum, maximum, skewness, and kurtosis, based on the boolean flags provided. Missing or NaN values are ignored when computing statistics. If all values are NaN for a band, NaN is returned for each statistic.

:param image: A multi-band spectral image where each band is represented in a separate 2D array. :type image: np.ndarray :param statistics_bands: List of band indices in the image for which statistics should be calculated. :type statistics_bands: List[int] :param calc_mean: Indicates whether to calculate the mean for the specified bands. :type calc_mean: bool :param calc_variance: Indicates whether to calculate the variance for the specified bands. :type calc_variance: bool :param calc_min: Indicates whether to calculate the minimum value for the specified bands. :type calc_min: bool :param calc_max: Indicates whether to calculate the maximum value for the specified bands. :type calc_max: bool :param calc_skewness: Indicates whether to calculate the skewness for the specified bands. :type calc_skewness: bool :param calc_kurtosis: Indicates whether to calculate the kurtosis for the specified bands. :type calc_kurtosis: bool :return: A dictionary containing the calculated statistics for each specified band, with keys formatted as 'b{band_index}_statistic'. :rtype: dict

Source code in obia/segmentation/segment_statistics.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def calculate_spectral_stats(
        image, statistics_bands,
        calc_mean=True, calc_variance=True, calc_min=True, calc_max=True, calc_skewness=True, calc_kurtosis=True
):
    """
    Calculates a range of statistical measures for specific bands of a spectral image. The statistics calculated are
    mean, variance, minimum, maximum, skewness, and kurtosis, based on the boolean flags provided. Missing or NaN
    values are ignored when computing statistics. If all values are NaN for a band, NaN is returned for each statistic.

    :param image: A multi-band spectral image where each band is represented in a separate 2D array.
    :type image: np.ndarray
    :param statistics_bands: List of band indices in the image for which statistics should be calculated.
    :type statistics_bands: List[int]
    :param calc_mean: Indicates whether to calculate the mean for the specified bands.
    :type calc_mean: bool
    :param calc_variance: Indicates whether to calculate the variance for the specified bands.
    :type calc_variance: bool
    :param calc_min: Indicates whether to calculate the minimum value for the specified bands.
    :type calc_min: bool
    :param calc_max: Indicates whether to calculate the maximum value for the specified bands.
    :type calc_max: bool
    :param calc_skewness: Indicates whether to calculate the skewness for the specified bands.
    :type calc_skewness: bool
    :param calc_kurtosis: Indicates whether to calculate the kurtosis for the specified bands.
    :type calc_kurtosis: bool
    :return: A dictionary containing the calculated statistics for each specified band, with keys formatted as
             'b{band_index}_statistic'.
    :rtype: dict
    """
    stats_dict = {}
    for band_index in statistics_bands:
        band_data = image[band_index, :, :]
        valid_mask = ~np.isnan(band_data)
        band_flat = band_data[valid_mask]

        band_prefix = f"b{band_index}"

        if band_flat.size == 0:
            if calc_mean:
                stats_dict[f"{band_prefix}_mean"] = np.nan
            if calc_variance:
                stats_dict[f"{band_prefix}_variance"] = np.nan
            if calc_min:
                stats_dict[f"{band_prefix}_min"] = np.nan
            if calc_max:
                stats_dict[f"{band_prefix}_max"] = np.nan
            if calc_skewness:
                stats_dict[f"{band_prefix}_skewness"] = np.nan
            if calc_kurtosis:
                stats_dict[f"{band_prefix}_kurtosis"] = np.nan
        else:
            if calc_mean:
                stats_dict[f"{band_prefix}_mean"] = np.mean(band_flat)
            if calc_variance:
                stats_dict[f"{band_prefix}_variance"] = np.var(band_flat)
            if calc_min:
                stats_dict[f"{band_prefix}_min"] = np.min(band_flat)
            if calc_max:
                stats_dict[f"{band_prefix}_max"] = np.max(band_flat)
            if calc_skewness:
                stats_dict[f"{band_prefix}_skewness"] = skew(band_flat)
            if calc_kurtosis:
                stats_dict[f"{band_prefix}_kurtosis"] = kurtosis(band_flat)
    return stats_dict

calculate_textural_stats(image, textural_bands, calc_contrast=True, calc_dissimilarity=True, calc_homogeneity=True, calc_ASM=True, calc_energy=True, calc_correlation=True)

Calculate textural statistics from a multi-band image based on specified bands. This function computes various textural properties such as contrast, dissimilarity, homogeneity, ASM, energy, and correlation. The calculations are performed on the specified bands of the input image, with options to select which statistics to compute. The results for each statistic are stored in a dictionary with the band index as the prefix to the keys.

:param image: The multi-band image from which textural statistics are calculated. :type image: numpy.ndarray :param textural_bands: Indices of the bands to be used for calculating textural statistics. :type textural_bands: list of int :param calc_contrast: Flag indicating whether to calculate contrast. :type calc_contrast: bool, optional :param calc_dissimilarity: Flag indicating whether to calculate dissimilarity. :type calc_dissimilarity: bool, optional :param calc_homogeneity: Flag indicating whether to calculate homogeneity. :type calc_homogeneity: bool, optional :param calc_ASM: Flag indicating whether to calculate ASM (angular second moment). :type calc_ASM: bool, optional :param calc_energy: Flag indicating whether to calculate energy. :type calc_energy: bool, optional :param calc_correlation: Flag indicating whether to calculate correlation. :type calc_correlation: bool, optional :return: A dictionary containing the computed textural statistics for each band. :rtype: dict

Source code in obia/segmentation/segment_statistics.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
def calculate_textural_stats(
        image, textural_bands,
        calc_contrast=True, calc_dissimilarity=True, calc_homogeneity=True,
        calc_ASM=True, calc_energy=True, calc_correlation=True
):
    """
    Calculate textural statistics from a multi-band image based on specified bands.
    This function computes various textural properties such as contrast,
    dissimilarity, homogeneity, ASM, energy, and correlation. The calculations
    are performed on the specified bands of the input image, with options to
    select which statistics to compute. The results for each statistic are
    stored in a dictionary with the band index as the prefix to the keys.

    :param image: The multi-band image from which textural statistics are calculated.
    :type image: numpy.ndarray
    :param textural_bands: Indices of the bands to be used for calculating textural statistics.
    :type textural_bands: list of int
    :param calc_contrast: Flag indicating whether to calculate contrast.
    :type calc_contrast: bool, optional
    :param calc_dissimilarity: Flag indicating whether to calculate dissimilarity.
    :type calc_dissimilarity: bool, optional
    :param calc_homogeneity: Flag indicating whether to calculate homogeneity.
    :type calc_homogeneity: bool, optional
    :param calc_ASM: Flag indicating whether to calculate ASM (angular second moment).
    :type calc_ASM: bool, optional
    :param calc_energy: Flag indicating whether to calculate energy.
    :type calc_energy: bool, optional
    :param calc_correlation: Flag indicating whether to calculate correlation.
    :type calc_correlation: bool, optional
    :return: A dictionary containing the computed textural statistics for each band.
    :rtype: dict
    """
    stats_dict = {}

    for band_index in textural_bands:
        band_data = image[:, :, band_index]
        valid_mask = ~np.isnan(band_data)

        if not np.any(valid_mask):
            if calc_contrast:
                stats_dict[f"b{band_index}_contrast"] = np.nan
            if calc_dissimilarity:
                stats_dict[f"b{band_index}_dissimilarity"] = np.nan
            if calc_homogeneity:
                stats_dict[f"b{band_index}_homogeneity"] = np.nan
            if calc_ASM:
                stats_dict[f"b{band_index}_ASM"] = np.nan
            if calc_energy:
                stats_dict[f"b{band_index}_energy"] = np.nan
            if calc_correlation:
                stats_dict[f"b{band_index}_correlation"] = np.nan
            continue

        if np.isnan(band_data[valid_mask]).any():
            if calc_contrast:
                stats_dict[f"b{band_index}_contrast"] = np.nan
            if calc_dissimilarity:
                stats_dict[f"b{band_index}_dissimilarity"] = np.nan
            if calc_homogeneity:
                stats_dict[f"b{band_index}_homogeneity"] = np.nan
            if calc_ASM:
                stats_dict[f"b{band_index}_ASM"] = np.nan
            if calc_energy:
                stats_dict[f"b{band_index}_energy"] = np.nan
            if calc_correlation:
                stats_dict[f"b{band_index}_correlation"] = np.nan
            continue

        band_clean = band_data.copy()
        band_clean[~valid_mask] = 0

        band_prefix = f"b{band_index}"

        if np.issubdtype(band_clean.dtype, np.integer):
            glcm_input = band_clean.astype(np.uint8)
        else:
            band_min, band_max = np.min(band_clean), np.max(band_clean)
            if band_max == band_min:
                glcm_input = np.zeros(band_clean.shape, dtype=np.uint8)
            else:
                glcm_input = ((band_clean - band_min) / (band_max - band_min) * 255).astype(np.uint8)

        try:
            glcm = graycomatrix(
                glcm_input,
                distances=[2],
                angles=[0, np.pi / 4, np.pi / 2, 3 * np.pi / 4],
                levels=256,
                symmetric=True,
                normed=True
            )
        except ValueError:
            if calc_contrast:
                stats_dict[f"{band_prefix}_contrast"] = np.nan
            if calc_dissimilarity:
                stats_dict[f"{band_prefix}_dissimilarity"] = np.nan
            if calc_homogeneity:
                stats_dict[f"{band_prefix}_homogeneity"] = np.nan
            if calc_ASM:
                stats_dict[f"{band_prefix}_ASM"] = np.nan
            if calc_energy:
                stats_dict[f"{band_prefix}_energy"] = np.nan
            if calc_correlation:
                stats_dict[f"{band_prefix}_correlation"] = np.nan
            continue

        if calc_contrast:
            stats_dict[f"{band_prefix}_contrast"] = np.mean(graycoprops(glcm, 'contrast'))
        if calc_dissimilarity:
            stats_dict[f"{band_prefix}_dissimilarity"] = np.mean(graycoprops(glcm, 'dissimilarity'))
        if calc_homogeneity:
            stats_dict[f"{band_prefix}_homogeneity"] = np.mean(graycoprops(glcm, 'homogeneity'))
        if calc_ASM:
            stats_dict[f"{band_prefix}_ASM"] = np.mean(graycoprops(glcm, 'ASM'))
        if calc_energy:
            stats_dict[f"{band_prefix}_energy"] = np.mean(graycoprops(glcm, 'energy'))
        if calc_correlation:
            stats_dict[f"{band_prefix}_correlation"] = np.mean(graycoprops(glcm, 'correlation'))

    return stats_dict

create_objects(segments, image, spectral_bands=None, textural_bands=None, calculate_spectral=True, calculate_textural=True, calc_mean=True, calc_variance=True, calc_min=True, calc_max=True, calc_skewness=True, calc_kurtosis=True, calc_contrast=True, calc_dissimilarity=True, calc_homogeneity=True, calc_ASM=True, calc_energy=True, calc_correlation=True)

:param segments: GeoDataFrame containing the segmented regions to be analyzed. :param image: Object containing image data and metadata to be used for analysis. Should have 'img_data' attribute as 3D NumPy array and 'crs' attribute. :param spectral_bands: Optional; List of spectral bands to be used in the analysis. Defaults to all available bands. :param textural_bands: Optional; List of textural bands to be used in the analysis. Defaults to all available bands. :param calculate_spectral: Boolean; Whether to calculate spectral statistics. Defaults to True. :param calculate_textural: Boolean; Whether to calculate textural statistics. Defaults to True. :param calc_mean: Boolean; Whether to calculate the mean of the pixel values. Defaults to True. :param calc_variance: Boolean; Whether to calculate the variance of the pixel values. Defaults to True. :param calc_min: Boolean; Whether to calculate the minimum of the pixel values. Defaults to True. :param calc_max: Boolean; Whether to calculate the maximum of the pixel values. Defaults to True. :param calc_skewness: Boolean; Whether to calculate the skewness of the pixel values. Defaults to True. :param calc_kurtosis: Boolean; Whether to calculate the kurtosis of the pixel values. Defaults to True. :param calc_contrast: Boolean; Whether to calculate the contrast for textural analysis. Defaults to True. :param calc_dissimilarity: Boolean; Whether to calculate the dissimilarity for textural analysis. Defaults to True. :param calc_homogeneity: Boolean; Whether to calculate the homogeneity for textural analysis. Defaults to True. :param calc_ASM: Boolean; Whether to calculate the Angular Second Moment (ASM) for textural analysis. Defaults to True. :param calc_energy: Boolean; Whether to calculate the energy for textural analysis. Defaults to True. :param calc_correlation: Boolean; Whether to calculate the correlation for textural analysis. Defaults to True. :return: GeoDataFrame containing the calculated statistics for each segment.

Source code in obia/segmentation/segment_statistics.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
def create_objects(
        segments, image, spectral_bands=None, textural_bands=None,
        calculate_spectral=True, calculate_textural=True,
        calc_mean=True, calc_variance=True, calc_min=True, calc_max=True, calc_skewness=True, calc_kurtosis=True,
        calc_contrast=True, calc_dissimilarity=True, calc_homogeneity=True, calc_ASM=True, calc_energy=True, calc_correlation=True
):
    """
    :param segments: GeoDataFrame containing the segmented regions to be analyzed.
    :param image: Object containing image data and metadata to be used for analysis. Should have 'img_data' attribute as 3D NumPy array and 'crs' attribute.
    :param spectral_bands: Optional; List of spectral bands to be used in the analysis. Defaults to all available bands.
    :param textural_bands: Optional; List of textural bands to be used in the analysis. Defaults to all available bands.
    :param calculate_spectral: Boolean; Whether to calculate spectral statistics. Defaults to True.
    :param calculate_textural: Boolean; Whether to calculate textural statistics. Defaults to True.
    :param calc_mean: Boolean; Whether to calculate the mean of the pixel values. Defaults to True.
    :param calc_variance: Boolean; Whether to calculate the variance of the pixel values. Defaults to True.
    :param calc_min: Boolean; Whether to calculate the minimum of the pixel values. Defaults to True.
    :param calc_max: Boolean; Whether to calculate the maximum of the pixel values. Defaults to True.
    :param calc_skewness: Boolean; Whether to calculate the skewness of the pixel values. Defaults to True.
    :param calc_kurtosis: Boolean; Whether to calculate the kurtosis of the pixel values. Defaults to True.
    :param calc_contrast: Boolean; Whether to calculate the contrast for textural analysis. Defaults to True.
    :param calc_dissimilarity: Boolean; Whether to calculate the dissimilarity for textural analysis. Defaults to True.
    :param calc_homogeneity: Boolean; Whether to calculate the homogeneity for textural analysis. Defaults to True.
    :param calc_ASM: Boolean; Whether to calculate the Angular Second Moment (ASM) for textural analysis. Defaults to True.
    :param calc_energy: Boolean; Whether to calculate the energy for textural analysis. Defaults to True.
    :param calc_correlation: Boolean; Whether to calculate the correlation for textural analysis. Defaults to True.
    :return: GeoDataFrame containing the calculated statistics for each segment.
    """
    if not (calculate_spectral or calculate_textural):
        raise ValueError(
            "At least one of 'calculate_spectral' or 'calculate_textural' must be True."
        )

    if spectral_bands is None:
        spectral_bands = list(range(image.img_data.shape[2]))
    if textural_bands is None:
        textural_bands = list(range(image.img_data.shape[2]))

    #
    # # ------------- KEY ADDITION -------------
    # # Filter out any band indices that exceed the number of bands in the image.
    # valid_spectral_bands = [b for b in spectral_bands if b < image.img_data.shape[0]]
    # if len(valid_spectral_bands) < len(spectral_bands):
    #     print(
    #         "Warning: Some spectral band indices were invalid and have been removed. "
    #         f"(Requested: {spectral_bands}, valid: {valid_spectral_bands})"
    #     )
    # spectral_bands = valid_spectral_bands
    #
    # valid_textural_bands = [b for b in textural_bands if b < image.img_data.shape[0]]
    # if len(valid_textural_bands) < len(textural_bands):
    #     print(
    #         "Warning: Some textural band indices were invalid and have been removed. "
    #         f"(Requested: {textural_bands}, valid: {valid_textural_bands})"
    #     )
    # textural_bands = valid_textural_bands
    # # ------------- END KEY ADDITION ----------

    columns = _create_empty_stats_columns(
        spectral_bands, textural_bands,
        calc_mean, calc_variance, calc_min, calc_max, calc_skewness, calc_kurtosis,
        calc_contrast, calc_dissimilarity, calc_homogeneity, calc_ASM, calc_energy, calc_correlation
    )

    results = []

    for i, (idx, segment) in enumerate(tqdm(segments.iterrows(), total=len(segments), desc="Processing Segments")):
        geom = segment.geometry
        segment_id = segment['segment_id']

        cropped_img_data, cropped_transform = crop_image_to_bbox(image, geom)
        masked_img_data = mask_image_with_polygon(cropped_img_data, geom, cropped_transform)

        row = {
            'segment_id': segment_id,
            'geometry': geom
        }

        spectral_statistics = calculate_spectral_stats(
            masked_img_data, spectral_bands,
            calc_mean=calc_mean, calc_variance=calc_variance, calc_min=calc_min,
            calc_max=calc_max, calc_skewness=calc_skewness, calc_kurtosis=calc_kurtosis
        )
        row.update(spectral_statistics)

        # --- 2) Textural stats
        if calculate_textural and textural_bands:
            textural_statistics = calculate_textural_stats(
                masked_img_data,
                textural_bands,
                calc_contrast=calc_contrast,
                calc_dissimilarity=calc_dissimilarity,
                calc_homogeneity=calc_homogeneity,
                calc_ASM=calc_ASM,
                calc_energy=calc_energy,
                calc_correlation=calc_correlation
            )
            row.update(textural_statistics)

        results.append(row)

    gdf = gpd.GeoDataFrame(results, columns=columns, crs=segments.crs)
    return gdf