Skip to content

Create Seamlines

Create footprints once, optionally postprocess them, then pass the resulting GeoPackage to either seamline method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from spectralmatch import (
    create_footprints, postprocess_footprints,
    voronoi_center_seamline, weighted_seamline,
)

footprints = create_footprints(
    "images/*.tif", "footprints.gpkg", image_threads=4,
)
cleaned = postprocess_footprints(
    footprints, "cleaned.gpkg",
    edge_distance=800, hole_to_hole_distance=800,
    cut_width="maximum_inscribed_circle", smoothing_radius=240,
    simplify_tolerance=120, area_filter=None, area_rank=1, image_threads=4,
)
voronoi_center_seamline(cleaned, "voronoi.gpkg")

# Add ranking attributes (e.g. quality) to the footprint layer before ranking.
weighted_seamline(cleaned, "weighted.gpkg", rank_function="{quality}")

These functions are also available as Seamline.create_footprints, Seamline.postprocess_footprints, Seamline.voronoi, and Seamline.weighted, and through the CLI. Voronoi now takes input_polygons, input_layer, and image_field_name; its former input_images and substring-based vector_mask inputs have been removed. Pipeline callers use voronoi_center_seamline_input_polygons and voronoi_center_seamline_input_layer. When no polygon input is supplied, the default pipeline explicitly calls create_footprints on its current images before invoking Voronoi.

create_footprints polygonizes the GDAL validity mask of band (default 1), including nodata, dataset masks, or alpha masks as provided by GDAL. It retains all islands and holes, with one feature per image and fields image (basename without extension) and image_path. Images must have unique basenames and the same CRS. A categorical cloud raster must first encode invalid pixels as nodata or a validity mask; its class values alone do not define validity. eight_connected controls diagonal connectivity. Polygonization explicitly supplies the raster georeferencing for mask bands through GDAL's DATASET_FOR_GEOREF option.

Postprocessing preserves attributes and requires a suitable projected CRS. Distances use that CRS's linear units. Both new functions accept image_threads, concurrent_processing_backend, dask_scheduler, debug_logs, and resume_from_outputs, following the package's existing execution conventions. Local raster polygonization uses threads, matching the existing raster-to-vector function; local geometry postprocessing uses processes. Dask dispatches both through the shared executor. Workers return geometries; the parent alone writes and flushes each feature as soon as it completes, before logging completion. Parallel outputs are stored in completion order, with attributes attached by input index. Completed features remain readable if another worker fails; an adjacent .incomplete marker prevents resume modes from mistaking a partial output for a completed one. Rerunning an incomplete output recomputes the layer.

Postprocessing parameter Effect
edge_distance=800 Maximum distance from a hole to its original component's outer ring; zero disables only hole-to-edge cuts.
hole_to_hole_distance=800 Maximum boundary-to-boundary distance between original holes in the same polygon component. Connects every qualifying pair; zero disables only hole-to-hole cuts.
relative_edge_distance=None Optional additional limit on hole-to-edge distance divided by sqrt(hole_area / pi). Does not restrict hole-to-hole cuts.
cut_width="maximum_inscribed_circle" Diameter of the largest circle fitting inside each hole, independent of cut direction. Also accepts "hole_size" for the largest vertex-to-vertex diameter or a positive integer for a fixed width. Applies to both cut types; hole pairs use the smaller of their two widths.
cut_method="corridor" Subtract a shortest connection buffered by half the cut width. With "buffer", expand an edge-selected hole by distance + width / 2, or both holes in a pair by (distance + width) / 2.
smoothing_radius=240 Erode then dilate, intersecting with the cut geometry to prevent expansion or refilling cuts.
simplify_tolerance=120 Maximum deviation of removed vertices from each shortcut; zero disables simplification.
simplify_area_weight=0.5 Balance normalized area loss against perimeter reduction; larger values favor retaining area.
area_filter=None Minimum polygon component area in squared CRS units; None disables the threshold.
area_rank=1 Keep the largest N components per feature for positive N or smallest abs(N) for negative N; 0 or None keeps all.

Area filtering runs after smoothing and simplification, first by threshold and then by rank, independently for each feature. Ranking does not remove interior holes from retained components.

Both distance limits use the original geometry, before any cuts or smoothing. Hole pairs are evaluated once, within each polygon component; separate components and features are never paired. A chain of qualifying hole pairs can connect a deep hole to an edge-selected hole, even when the deep hole itself exceeds edge_distance. Newly cut boundaries do not make additional pairs or edge cuts eligible. Set both distance parameters to 0 to disable explicit cuts; smoothing can still connect holes by removing narrow strips.

The maximum inscribed circle width measures the hole's thickest interior region: a 1000-by-200 rectangle produces a width of approximately 200 at any rotation. The radius is approximated to a tolerance of sqrt(hole_area) / 1000; the width is twice that radius. For an irregular hole with a large lobe and a narrow neck, the large lobe determines the width. Other holes can still be reached by wide cuts, overlapping corridors, or smoothing. Holes are not filled. Empty processed features are omitted; removing every feature raises an error.

The simplifier is an inward greedy adaptation of the vertex-restricted shortcut idea in Shortcut Hulls (Bonerath et al., 2021). The paper's algorithm constructs outer hulls and optimizes globally; this implementation does neither. It uses a priority queue of vertex removals, cached area and coordinate arithmetic for shortcut costs and displacement, and a spatial index of boundary vertices for local inward-ear checks. It balances normalized area loss and perimeter savings and bounds cumulative shortcut displacement. A final validity and containment check retains the input if numerical degeneracies defeat the local checks. Exterior and hole rings retain at least three vertices. It therefore cannot expand the valid region or fill a cloud hole. It is a local heuristic, and may leave vertices that a global optimizer could remove. Geometry checks can still be costly for very detailed footprints. Smoothing may introduce vertices before simplification; shortcut endpoints come from the geometry entering the simplifier.

Source code in spectralmatch/seamline/seamline.py
 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
 79
 80
 81
 82
 83
 84
 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
149
150
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
class Seamline:
    create_footprints = staticmethod(create_footprints)
    postprocess_footprints = staticmethod(postprocess_footprints)

    @staticmethod
    def weighted(
        input_polygons: str,
        output_mask: str,
        *,
        rank_function: str,
        image_field_name: str = "image",
        input_layer: str | None = None,
        output_layer: str = "seamlines",
        rank_descending: bool = True,
        debug_logs: Universal.DebugLogs = False,
        resume_from_outputs: Literal["no", "yes", "validate"] = "no",
    ) -> str:
        """Generate seamline polygons by ranking image footprints with a weighted expression.

Args:
    input_polygons (str): Input polygon layer path. Each feature should represent an image footprint or a piece of one.
    output_mask (str): Output GeoPackage path for the ranked seamline polygons.
    rank_function (str): Ranking expression using field placeholders like ``{cloud_cover}`` or formulas like ``1 / ({sun_elevation} + 1)``.
    image_field_name (str, optional): Field containing the image identifier. Features sharing the same value are merged before ranking. Defaults to ``"image"``.
    input_layer (str | None, optional): Optional input layer name when reading multi-layer vector sources. Defaults to None.
    output_layer (str, optional): Output GeoPackage layer name. Defaults to ``"seamlines"``.
    rank_descending (bool, optional): If True, larger scores rank higher and remain on top. Defaults to True.
    debug_logs (bool, optional): If True, prints ranking details. Defaults to False.

    resume_from_outputs (Literal["no", "yes", "validate"], optional): Recompute outputs with "no", reuse existing outputs with "yes", or validate existing outputs before reusing them with "validate"; default is "no".

Returns:
    str: Written output GeoPackage path."""
        _print_step_start("weighted_seamline")
        SeamlineValidation._validate_weighted_seamline(
            input_polygons=input_polygons,
            output_mask=output_mask,
            rank_function=rank_function,
            image_field_name=image_field_name,
            input_layer=input_layer,
            output_layer=output_layer,
            rank_descending=rank_descending,
        )
        if debug_logs:
            print(f"Input polygons: {input_polygons}")
            print(f"Output mask: {output_mask}")
            print(f"Rank function: {rank_function}")
        if _existing_outputs_are_reusable(
            [output_mask],
            resume_mode=resume_from_outputs,
            debug_logs=debug_logs,
            step_name="weighted_seamline",
        ):
            return output_mask
        _print_image_start(input_polygons, output_mask)
        result = weighted_seamline(
            input_polygons=input_polygons,
            output_mask=output_mask,
            rank_function=rank_function,
            image_field_name=image_field_name,
            input_layer=input_layer,
            output_layer=output_layer,
            rank_descending=rank_descending,
            debug_logs=debug_logs,
        )
        _print_image_completed(input_polygons, 1, 1)
        return result

    @staticmethod
    def voronoi(
        input_polygons: str,
        output_mask: str,
        *,
        aoi_path: str | None = None,
        input_layer: str | None = None,
        output_layer: str = "seamlines",
        image_field_name: str = "image",
        min_point_spacing: float = 10,
        min_cut_length: float = 0,
        debug_logs: Universal.DebugLogs = False,
        debug_vectors_path: str | None = None,
        resume_from_outputs: Literal["no", "yes", "validate"] = "no",
    ) -> str:
        """Generates a Voronoi-based seamline mask from edge-matching polygons (EMPs) and writes the result to a vector file.

Args:
    input_polygons (str): Input polygon layer path. Each feature should represent an image footprint or a piece of one. Features sharing the same image identifier are merged before processing.
    input_layer (str | None, optional): Optional input layer name when reading multi-layer vector sources. Defaults to None.
    output_layer (str, optional): Output GeoPackage layer name. Defaults to ``"seamlines"``.
    output_mask (str): Output path for the final seamline polygon vector file.
    aoi_path (str, optional): Path to an AOI vector file to clip overlapping image polygons; default is None.
    min_point_spacing (float, optional): Minimum spacing between Voronoi seed points; default is 10.
    min_cut_length (float, optional): Minimum cutline segment length to retain; default is 0.
    debug_logs (Universal.DebugLogs, optional): Enables debug print statements if True; default is False.
    image_field_name (str, optional): Name of the attribute field for image ID in output; default is 'image'.
    debug_vectors_path (str | None, optional): Optional path to save debug layers (cutlines, intersections).

    resume_from_outputs (Literal["no", "yes", "validate"], optional): Recompute outputs with "no", reuse existing outputs with "yes", or validate existing outputs before reusing them with "validate"; default is "no".

Returns:
    str: Written output GeoPackage path.

Outputs:
    Saves a polygon seamline layer to `output_mask`, and optionally saves intermediate cutlines to `debug_vectors_path`."""
        _print_step_start("voronoi_center_seamline")
        output_dir = os.path.dirname(output_mask)
        if output_dir:
            os.makedirs(output_dir, exist_ok=True)
        if debug_vectors_path:
            debug_dir = os.path.dirname(debug_vectors_path)
            if debug_dir:
                os.makedirs(debug_dir, exist_ok=True)
        if _existing_outputs_are_reusable(
            [output_mask],
            resume_mode=resume_from_outputs,
            debug_logs=debug_logs,
            step_name="voronoi_center_seamline",
        ):
            return output_mask
        SeamlineValidation._validate_voronoi_center_seamline(
            output_mask=output_mask,
            aoi_path=aoi_path,
            image_field_name=image_field_name,
            min_point_spacing=min_point_spacing,
            min_cut_length=min_cut_length,
            debug_vectors_path=debug_vectors_path,
        )
        SeamlineValidation._validate_weighted_seamline(
            input_polygons=input_polygons,
            input_layer=input_layer,
            output_layer=output_layer,
            image_field_name=image_field_name,
        )
        frame = _read_polygons(input_polygons, input_layer, image_field_name)
        crs = frame.crs.to_wkt()
        emps, input_image_names = [], []
        for image_name, group in frame.groupby(image_field_name, sort=False):
            # Process every island independently; merge by image ID when writing.
            parts = _polygon_parts(unary_union(list(group.geometry)))
            emps.extend(parts)
            input_image_names.extend([str(image_name)] * len(parts))
        input_image_paths = input_image_names
        for image_name in input_image_names:
            _print_image_start(f"{input_polygons}:{image_name}", output_mask)

        image_details = [
            (
                {"Footprint area": f"{emp.area:.2f}", "Bounds": str(emp.bounds)}
                if debug_logs
                else {}
            )
            for emp in emps
        ]

        if debug_vectors_path:
            if os.path.exists(debug_vectors_path):
                os.remove(debug_vectors_path)
            _save_emp_outlines(
                emps,
                input_image_paths,
                debug_vectors_path,
                crs,
                image_field_name=image_field_name,
            )

        cuts: list[LineString] = []
        for i, (left, right) in enumerate(combinations(range(len(emps)), 2)):
            if input_image_names[left] == input_image_names[right]:
                continue
            a, b = emps[left], emps[right]
            ov = a.intersection(b)
            if debug_logs:
                print(f"Overlap {i} area: {ov.area:.2f}")
            if ov.area > 0:
                if debug_vectors_path:
                    _save_intersection_points(a, b, debug_vectors_path, crs, f"{i}")
                cut = _compute_centerline(
                    a,
                    b,
                    min_point_spacing,
                    min_cut_length,
                    debug_logs,
                    crs,
                    debug_vectors_path,
                )
                cuts.append(cut)

        if debug_vectors_path:
            schema = {"geometry": "LineString", "properties": {"pair_id": "str"}}
            with fiona.open(
                debug_vectors_path,
                "w",
                driver="GPKG",
                crs_wkt=crs,
                schema=schema,
                layer="cutlines",
            ) as dst:
                for idx, line in enumerate(cuts):
                    dst.write(
                        {
                            "geometry": mapping(line),
                            "properties": {"pair_id": f"{idx}"},
                        }
                    )

        segmented: list[Polygon] = []
        for idx, emp in enumerate(emps):
            relevant = [cut for cut in cuts if emp.intersects(cut)]
            seg = _segment_emp(emp, relevant, debug_logs)
            if debug_logs:
                image_details[idx].update(
                    {"Cuts": len(relevant), "Segmented area": f"{seg.area:.2f}"}
                )
            segmented.append(seg)

        if aoi_path is not None:
            segmented = _mask_by_aoi(segmented, aoi_path)

        schema = {"geometry": "MultiPolygon", "properties": {image_field_name: "str"}}
        with fiona.open(
            output_mask,
            "w",
            driver="GPKG",
            crs_wkt=crs,
            schema=schema,
            layer=output_layer,
        ) as dst:
            from shapely.geometry import MultiPolygon

            grouped = {}
            for image_name, poly in zip(input_image_names, segmented):
                grouped.setdefault(image_name, []).extend(_polygon_parts(poly))
            for image_name, parts in grouped.items():
                if parts:
                    dst.write(
                        {
                            "geometry": mapping(
                                MultiPolygon(_polygon_parts(unary_union(parts)))
                            ),
                            "properties": {image_field_name: image_name},
                        }
                    )

        for completed, path in enumerate(input_image_paths, 1):
            _print_image_completed(
                path,
                completed,
                len(input_image_paths),
                details=image_details[completed - 1],
            )

        return output_mask

voronoi(input_polygons, output_mask, *, aoi_path=None, input_layer=None, output_layer='seamlines', image_field_name='image', min_point_spacing=10, min_cut_length=0, debug_logs=False, debug_vectors_path=None, resume_from_outputs='no') staticmethod

Generates a Voronoi-based seamline mask from edge-matching polygons (EMPs) and writes the result to a vector file.

Parameters:

Name Type Description Default
input_polygons str

Input polygon layer path. Each feature should represent an image footprint or a piece of one. Features sharing the same image identifier are merged before processing.

required
input_layer str | None

Optional input layer name when reading multi-layer vector sources. Defaults to None.

None
output_layer str

Output GeoPackage layer name. Defaults to "seamlines".

'seamlines'
output_mask str

Output path for the final seamline polygon vector file.

required
aoi_path str

Path to an AOI vector file to clip overlapping image polygons; default is None.

None
min_point_spacing float

Minimum spacing between Voronoi seed points; default is 10.

10
min_cut_length float

Minimum cutline segment length to retain; default is 0.

0
debug_logs DebugLogs

Enables debug print statements if True; default is False.

False
image_field_name str

Name of the attribute field for image ID in output; default is 'image'.

'image'
debug_vectors_path str | None

Optional path to save debug layers (cutlines, intersections).

None
resume_from_outputs Literal['no', 'yes', 'validate']

Recompute outputs with "no", reuse existing outputs with "yes", or validate existing outputs before reusing them with "validate"; default is "no".

'no'

Returns:

Name Type Description
str str

Written output GeoPackage path.

Outputs

Saves a polygon seamline layer to output_mask, and optionally saves intermediate cutlines to debug_vectors_path.

Source code in spectralmatch/seamline/seamline.py
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
149
150
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
    @staticmethod
    def voronoi(
        input_polygons: str,
        output_mask: str,
        *,
        aoi_path: str | None = None,
        input_layer: str | None = None,
        output_layer: str = "seamlines",
        image_field_name: str = "image",
        min_point_spacing: float = 10,
        min_cut_length: float = 0,
        debug_logs: Universal.DebugLogs = False,
        debug_vectors_path: str | None = None,
        resume_from_outputs: Literal["no", "yes", "validate"] = "no",
    ) -> str:
        """Generates a Voronoi-based seamline mask from edge-matching polygons (EMPs) and writes the result to a vector file.

Args:
    input_polygons (str): Input polygon layer path. Each feature should represent an image footprint or a piece of one. Features sharing the same image identifier are merged before processing.
    input_layer (str | None, optional): Optional input layer name when reading multi-layer vector sources. Defaults to None.
    output_layer (str, optional): Output GeoPackage layer name. Defaults to ``"seamlines"``.
    output_mask (str): Output path for the final seamline polygon vector file.
    aoi_path (str, optional): Path to an AOI vector file to clip overlapping image polygons; default is None.
    min_point_spacing (float, optional): Minimum spacing between Voronoi seed points; default is 10.
    min_cut_length (float, optional): Minimum cutline segment length to retain; default is 0.
    debug_logs (Universal.DebugLogs, optional): Enables debug print statements if True; default is False.
    image_field_name (str, optional): Name of the attribute field for image ID in output; default is 'image'.
    debug_vectors_path (str | None, optional): Optional path to save debug layers (cutlines, intersections).

    resume_from_outputs (Literal["no", "yes", "validate"], optional): Recompute outputs with "no", reuse existing outputs with "yes", or validate existing outputs before reusing them with "validate"; default is "no".

Returns:
    str: Written output GeoPackage path.

Outputs:
    Saves a polygon seamline layer to `output_mask`, and optionally saves intermediate cutlines to `debug_vectors_path`."""
        _print_step_start("voronoi_center_seamline")
        output_dir = os.path.dirname(output_mask)
        if output_dir:
            os.makedirs(output_dir, exist_ok=True)
        if debug_vectors_path:
            debug_dir = os.path.dirname(debug_vectors_path)
            if debug_dir:
                os.makedirs(debug_dir, exist_ok=True)
        if _existing_outputs_are_reusable(
            [output_mask],
            resume_mode=resume_from_outputs,
            debug_logs=debug_logs,
            step_name="voronoi_center_seamline",
        ):
            return output_mask
        SeamlineValidation._validate_voronoi_center_seamline(
            output_mask=output_mask,
            aoi_path=aoi_path,
            image_field_name=image_field_name,
            min_point_spacing=min_point_spacing,
            min_cut_length=min_cut_length,
            debug_vectors_path=debug_vectors_path,
        )
        SeamlineValidation._validate_weighted_seamline(
            input_polygons=input_polygons,
            input_layer=input_layer,
            output_layer=output_layer,
            image_field_name=image_field_name,
        )
        frame = _read_polygons(input_polygons, input_layer, image_field_name)
        crs = frame.crs.to_wkt()
        emps, input_image_names = [], []
        for image_name, group in frame.groupby(image_field_name, sort=False):
            # Process every island independently; merge by image ID when writing.
            parts = _polygon_parts(unary_union(list(group.geometry)))
            emps.extend(parts)
            input_image_names.extend([str(image_name)] * len(parts))
        input_image_paths = input_image_names
        for image_name in input_image_names:
            _print_image_start(f"{input_polygons}:{image_name}", output_mask)

        image_details = [
            (
                {"Footprint area": f"{emp.area:.2f}", "Bounds": str(emp.bounds)}
                if debug_logs
                else {}
            )
            for emp in emps
        ]

        if debug_vectors_path:
            if os.path.exists(debug_vectors_path):
                os.remove(debug_vectors_path)
            _save_emp_outlines(
                emps,
                input_image_paths,
                debug_vectors_path,
                crs,
                image_field_name=image_field_name,
            )

        cuts: list[LineString] = []
        for i, (left, right) in enumerate(combinations(range(len(emps)), 2)):
            if input_image_names[left] == input_image_names[right]:
                continue
            a, b = emps[left], emps[right]
            ov = a.intersection(b)
            if debug_logs:
                print(f"Overlap {i} area: {ov.area:.2f}")
            if ov.area > 0:
                if debug_vectors_path:
                    _save_intersection_points(a, b, debug_vectors_path, crs, f"{i}")
                cut = _compute_centerline(
                    a,
                    b,
                    min_point_spacing,
                    min_cut_length,
                    debug_logs,
                    crs,
                    debug_vectors_path,
                )
                cuts.append(cut)

        if debug_vectors_path:
            schema = {"geometry": "LineString", "properties": {"pair_id": "str"}}
            with fiona.open(
                debug_vectors_path,
                "w",
                driver="GPKG",
                crs_wkt=crs,
                schema=schema,
                layer="cutlines",
            ) as dst:
                for idx, line in enumerate(cuts):
                    dst.write(
                        {
                            "geometry": mapping(line),
                            "properties": {"pair_id": f"{idx}"},
                        }
                    )

        segmented: list[Polygon] = []
        for idx, emp in enumerate(emps):
            relevant = [cut for cut in cuts if emp.intersects(cut)]
            seg = _segment_emp(emp, relevant, debug_logs)
            if debug_logs:
                image_details[idx].update(
                    {"Cuts": len(relevant), "Segmented area": f"{seg.area:.2f}"}
                )
            segmented.append(seg)

        if aoi_path is not None:
            segmented = _mask_by_aoi(segmented, aoi_path)

        schema = {"geometry": "MultiPolygon", "properties": {image_field_name: "str"}}
        with fiona.open(
            output_mask,
            "w",
            driver="GPKG",
            crs_wkt=crs,
            schema=schema,
            layer=output_layer,
        ) as dst:
            from shapely.geometry import MultiPolygon

            grouped = {}
            for image_name, poly in zip(input_image_names, segmented):
                grouped.setdefault(image_name, []).extend(_polygon_parts(poly))
            for image_name, parts in grouped.items():
                if parts:
                    dst.write(
                        {
                            "geometry": mapping(
                                MultiPolygon(_polygon_parts(unary_union(parts)))
                            ),
                            "properties": {image_field_name: image_name},
                        }
                    )

        for completed, path in enumerate(input_image_paths, 1):
            _print_image_completed(
                path,
                completed,
                len(input_image_paths),
                details=image_details[completed - 1],
            )

        return output_mask

weighted(input_polygons, output_mask, *, rank_function, image_field_name='image', input_layer=None, output_layer='seamlines', rank_descending=True, debug_logs=False, resume_from_outputs='no') staticmethod

Generate seamline polygons by ranking image footprints with a weighted expression.

Parameters:

Name Type Description Default
input_polygons str

Input polygon layer path. Each feature should represent an image footprint or a piece of one.

required
output_mask str

Output GeoPackage path for the ranked seamline polygons.

required
rank_function str

Ranking expression using field placeholders like {cloud_cover} or formulas like 1 / ({sun_elevation} + 1).

required
image_field_name str

Field containing the image identifier. Features sharing the same value are merged before ranking. Defaults to "image".

'image'
input_layer str | None

Optional input layer name when reading multi-layer vector sources. Defaults to None.

None
output_layer str

Output GeoPackage layer name. Defaults to "seamlines".

'seamlines'
rank_descending bool

If True, larger scores rank higher and remain on top. Defaults to True.

True
debug_logs bool

If True, prints ranking details. Defaults to False.

False
resume_from_outputs Literal['no', 'yes', 'validate']

Recompute outputs with "no", reuse existing outputs with "yes", or validate existing outputs before reusing them with "validate"; default is "no".

'no'

Returns:

Name Type Description
str str

Written output GeoPackage path.

Source code in spectralmatch/seamline/seamline.py
 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
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
    @staticmethod
    def weighted(
        input_polygons: str,
        output_mask: str,
        *,
        rank_function: str,
        image_field_name: str = "image",
        input_layer: str | None = None,
        output_layer: str = "seamlines",
        rank_descending: bool = True,
        debug_logs: Universal.DebugLogs = False,
        resume_from_outputs: Literal["no", "yes", "validate"] = "no",
    ) -> str:
        """Generate seamline polygons by ranking image footprints with a weighted expression.

Args:
    input_polygons (str): Input polygon layer path. Each feature should represent an image footprint or a piece of one.
    output_mask (str): Output GeoPackage path for the ranked seamline polygons.
    rank_function (str): Ranking expression using field placeholders like ``{cloud_cover}`` or formulas like ``1 / ({sun_elevation} + 1)``.
    image_field_name (str, optional): Field containing the image identifier. Features sharing the same value are merged before ranking. Defaults to ``"image"``.
    input_layer (str | None, optional): Optional input layer name when reading multi-layer vector sources. Defaults to None.
    output_layer (str, optional): Output GeoPackage layer name. Defaults to ``"seamlines"``.
    rank_descending (bool, optional): If True, larger scores rank higher and remain on top. Defaults to True.
    debug_logs (bool, optional): If True, prints ranking details. Defaults to False.

    resume_from_outputs (Literal["no", "yes", "validate"], optional): Recompute outputs with "no", reuse existing outputs with "yes", or validate existing outputs before reusing them with "validate"; default is "no".

Returns:
    str: Written output GeoPackage path."""
        _print_step_start("weighted_seamline")
        SeamlineValidation._validate_weighted_seamline(
            input_polygons=input_polygons,
            output_mask=output_mask,
            rank_function=rank_function,
            image_field_name=image_field_name,
            input_layer=input_layer,
            output_layer=output_layer,
            rank_descending=rank_descending,
        )
        if debug_logs:
            print(f"Input polygons: {input_polygons}")
            print(f"Output mask: {output_mask}")
            print(f"Rank function: {rank_function}")
        if _existing_outputs_are_reusable(
            [output_mask],
            resume_mode=resume_from_outputs,
            debug_logs=debug_logs,
            step_name="weighted_seamline",
        ):
            return output_mask
        _print_image_start(input_polygons, output_mask)
        result = weighted_seamline(
            input_polygons=input_polygons,
            output_mask=output_mask,
            rank_function=rank_function,
            image_field_name=image_field_name,
            input_layer=input_layer,
            output_layer=output_layer,
            rank_descending=rank_descending,
            debug_logs=debug_logs,
        )
        _print_image_completed(input_polygons, 1, 1)
        return result