API Reference¶
NickySpatial: An open-source object-based image analysis library for remote sensing¶
NickySpatial is a Python package for object-based image analysis, providing functionality similar to commercial software like eCognition.
Key features: - Multiresolution segmentation - Object-based analysis - Rule-based classification - Statistics calculation - Integration with geospatial data formats
nickyspatial.core
¶
The core package encompasses fundamental data structures and algorithms for nickyspatial.
It helps define the building blocks like layers, segmentation methods, and rule-based logic for object analysis workflows.
Implements supervised classification algorithms to classify the segments.
SupervisedClassifier
¶
Implementation of Supervised Classification algorithm.
Source code in nickyspatial/core/classifier.py
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 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 |
|
__init__(name=None, classifier_type='Random Forests', classifier_params=None)
¶
Initialize the segmentation algorithm.
Parameters:¶
scale : str classifier type name eg: RF for Random Forest, SVC for Support Vector Classifier classifier_params : dict additional parameters relayed to classifier
Source code in nickyspatial/core/classifier.py
execute(source_layer, samples, layer_manager=None, layer_name=None, features=None)
¶
Execute the supervised classification workflow on the source layer.
This method creates a new layer by copying the input source layer, training a classifier using provided samples, predicting classifications, and storing the results in a new layer. Optionally, the resulting layer can be added to a layer manager.
Parameters¶
source_layer : Layer The input layer containing spatial objects and metadata (transform, CRS, raster). samples : dict A dictionary of training samples where keys are class labels and values are lists of segment IDs or features used for training. Default is an empty dictionary. layer_manager : LayerManager, optional An optional layer manager object used to manage and store the resulting layer. layer_name : str, optional The name to assign to the resulting classified layer.
Returns:¶
Layer A new Layer object containing the predicted classifications, copied metadata from the source layer, and updated attributes.
Source code in nickyspatial/core/classifier.py
SupervisedClassifierDL
¶
Implementation of deep learning based supervised classification.
Source code in nickyspatial/core/classifier.py
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 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 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 |
|
__init__(name='CNN_Classification', classifier_type='Convolution Neural Network (CNN)', classifier_params=None)
¶
Initialize a Convolutional Neural Network (CNN) classifier.
Parameters¶
name : str, optional Custom name for the classification layer. Defaults to "CNN_Classification" if None. classifier_type : str, optional Type of classifier. Defaults to "Convolution Neural Network (CNN)". classifier_params : dict, optional Dictionary of training parameters for the CNN. If None, the following defaults are used: - epochs (int): 50 - batch_size (int): 32 - patch_size (tuple of int): (5, 5) - early_stopping_patience (int): 5
Source code in nickyspatial/core/classifier.py
execute(source_layer, samples, image_data, layer_manager=None, layer_name=None)
¶
Perform CNN-based classification on image segments using labeled training samples.
This method extracts training patches from the input image based on provided samples, trains a CNN model, evaluates it on test data, predicts labels for all segments, and stores the classification results in a new output layer.
Parameters¶
source_layer : Layer Input spatial layer containing segments/objects to classify. samples : dict Dictionary mapping class names to lists of segment IDs used for training. image_data : np.ndarray Raster image data array from which patches are extracted for classification. layer_manager : LayerManager, optional manager object to register the output classification layer. layer_name : str, optional The name to assign to the resulting classified layer.
Returns:¶
result_layer : Layer New layer containing the original segments with a "classification" attribute representing predicted class labels. history : keras.callbacks.History Training history object containing loss and accuracy metrics per epoch. eval_result : dict Dictionary containing evaluation metrics such as accuracy, confusion matrix, and classification report on the test dataset. count_dict : dict Dictionary mapping class labels to the count of training patches extracted. invalid_patches_segments_ids : list List of segment IDs for which no valid patches could be extracted for prediction.
Source code in nickyspatial/core/classifier.py
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 |
|
Layer class and related functionality for organizing geospatial data.
Layer
¶
A Layer represents a set of objects with associated properties.
Source code in nickyspatial/core/layer.py
__init__(name=None, parent=None, layer_type='generic')
¶
Initialize Layer with unique ID and optional name/parent.
Source code in nickyspatial/core/layer.py
__str__()
¶
Return layer info: name, type, and data availability.
Source code in nickyspatial/core/layer.py
attach_function(function, name=None, **kwargs)
¶
Attach and execute function, store result for later retrieval.
Source code in nickyspatial/core/layer.py
copy()
¶
Create independent copy with deep-copied raster/objects data.
Source code in nickyspatial/core/layer.py
get_function_result(function_name)
¶
Retrieve stored result from previously attached function.
Source code in nickyspatial/core/layer.py
LayerManager
¶
Manages a collection of layers and their relationships.
Source code in nickyspatial/core/layer.py
__init__()
¶
add_layer(layer, set_active=True)
¶
Add layer to manager, optionally set as active layer.
get_layer(layer_id_or_name)
¶
Find layer by ID first, then by name if not found.
Source code in nickyspatial/core/layer.py
get_layer_names()
¶
remove_layer(layer_id_or_name)
¶
Remove a layer from the manager.
Source code in nickyspatial/core/layer.py
Provides a rule engine for object-based analysis, where segments or layers are processed according to custom logic.
Main idea here is to allow encode expert rules that can be applied to object segments which are layers in a nickyspatial context. So rules are tied up to the layers , they can be attached or revoked or executed multiple items
Developers can define domain-specific rules to classify or merge features based on attributes. This module includes the Rule and RuleSet classes, which allow users to create, manage, and apply rules to layers. The RuleSet class can be used to group multiple rules together, and the execute method applies these rules to a given layer. The rules can be defined using string expressions that can be evaluated using the numexpr library for performance.
CommonBase
¶
A shared utility base class for spatial rule sets.
This class provides common methods used by multiple rule sets to preprocess layer data and determine spatial relationships between segments.
Source code in nickyspatial/core/rules.py
EnclosedByRuleSet
¶
Bases: CommonBase
A rule set to reclassify segments based on spatial enclosure.
This rule set identifies segments of one class (A) that are entirely surrounded by segments of another class (B), and reclassifies them into a new class.
Source code in nickyspatial/core/rules.py
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 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 |
|
__init__(name=None)
¶
execute(source_layer, class_column_name, class_value_a, class_value_b, new_class_name, layer_manager=None, layer_name=None)
¶
Apply enclosed-by logic to identify and reclassify segments.
Parameters:¶
source_layer : Layer The source spatial layer containing segments. class_column_name : str The name of the column containing class labels (e.g., "veg_class"). class_value_a : str The class value to check for enclosure (target to reclassify). class_value_b : str The class value expected to surround class A segments. new_class_name : str The new class name to assign to enclosed segments. layer_manager : LayerManager, optional Optional manager to register the resulting layer. layer_name : str, optional Optional name for the result layer.
Returns:¶
result_layer : Layer A new layer with updated class values for enclosed segments.
Source code in nickyspatial/core/rules.py
MergeRuleSet
¶
Bases: CommonBase
A rule set for merging segments of the same class based on specified class values.
Source code in nickyspatial/core/rules.py
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 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 |
|
__init__(name=None)
¶
execute(source_layer, class_column_name, class_value, layer_manager=None, layer_name=None)
¶
Merge segments of the same class in a layer.
Parameters:¶
source_layer : Layer Source layer with segments to merge class_value : str or list of str One or more attribute field names to group and merge segments layer_manager : LayerManager, optional Layer manager to add the result layer to layer_name : str, optional Name for the result layer
Returns:¶
result_layer : Layer Layer with merged geometries
Source code in nickyspatial/core/rules.py
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 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 |
|
Rule
¶
A rule defines a condition to classify segments.
Source code in nickyspatial/core/rules.py
__init__(name, condition, class_value=None)
¶
Initialize a rule.
Parameters:¶
name : str Name of the rule condition : str Condition as a string expression that can be evaluated using numexpr class_value : str, optional Value to assign when the condition is met. If None, uses the rule name.
Source code in nickyspatial/core/rules.py
RuleSet
¶
A collection of rules to apply to a layer.
Source code in nickyspatial/core/rules.py
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 |
|
add_rule(name, condition, class_value=None)
¶
Add a rule to the rule set.
Parameters:¶
name : str Name of the rule condition : str Condition as a string expression that can be evaluated using numexpr class_value : str, optional Value to assign when the condition is met
Returns:¶
rule : Rule The added rule
Source code in nickyspatial/core/rules.py
execute(source_layer, layer_manager=None, layer_name=None, result_field='classification')
¶
Apply rules to classify segments in a layer.
Parameters:¶
source_layer : Layer Source layer with segments to classify layer_manager : LayerManager, optional Layer manager to add the result layer to layer_name : str, optional Name for the result layer result_field : str Field name to store classification results
Returns:¶
result_layer : Layer Layer with classification results
Source code in nickyspatial/core/rules.py
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 |
|
get_rules()
¶
Get the list of rules in the rule set.
Returns:¶
list of tuples List of (name, condition) tuples for each rule
wrap_condition_parts_simple(condition)
staticmethod
¶
Wrap condition parts with parentheses for evaluation.
TouchedByRuleSet
¶
Bases: CommonBase
A rule set to reclassify segments based on spatial enclosure.
This rule set identifies segments of one class (A) that are entirely surrounded by segments of another class (B), and reclassifies them into a new class.
Source code in nickyspatial/core/rules.py
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 |
|
__init__(name=None)
¶
execute(source_layer, class_column_name, class_value_a, class_value_b, new_class_name, layer_manager=None, layer_name=None)
¶
Executes the merge rule set by identifying and updating segments of a given class that are adjacent to another class!
- source_layer: Layer The input layer containing segment geometries and attributes.
- class_column_name: str The name of the column containing class labels.
- class_value_a: str or int The class value of segments to be checked for touching neighbors.
- class_value_b: str or int The class value of neighboring segments that would trigger a merge.
- new_class_name: str The new class value to assign to segments of class_value_a that touch class_value_b.
- layer_manager: optional An optional manager for adding the resulting layer to a collection or interface.
- layer_name: optional
Optional custom name for the resulting layer. Defaults to "
_ ".
- result_layer: Layer A new Layer object with updated segment classifications where applicable.
Logic: - Copies the source layer and initializes a new result layer. - Preprocesses the source layer to build geometry and class lookup maps. - Iterates through each segment of class_value_a, checking if any of its neighbors belong to class_value_b. - If so, updates the segment's class to new_class_name. - Stores the modified DataFrame in the result layer and optionally registers it via the layer_manager.
Source code in nickyspatial/core/rules.py
Implements segmentation algorithms to partition images into meaningful region objects.
The functions here might apply clustering or region-growing techniques, aiding object-based remote sensing analysis. This module includes the SlicSegmentation class, which implements a bottom-up region-growing algorithm Algorithms: - SlicSegmentation: Bottom-up region-growing algorithm - FelzenszwalbSegmentation: Graph-based segmentation - WatershedSegmentation: Topographic watershed algorithm - RegularGridSegmentation: Simple grid-based segmentation
BaseSegmentation
¶
Base class for segmentation algorithms.
Source code in nickyspatial/core/segmentation.py
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 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 |
|
FelzenszwalbSegmentation
¶
Bases: BaseSegmentation
Implementation of Felzenszwalb's efficient graph-based segmentation.
This algorithm builds a graph of pixel similarities and uses a minimum spanning tree approach to segment the image into regions of similar characteristics.
Source code in nickyspatial/core/segmentation.py
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 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 |
|
__init__(scale=100, sigma=0.5, min_size=50, **kwargs)
¶
Initialize the Felzenszwalb segmentation algorithm.
Parameters:¶
scale : float Free parameter that influences the size of the segments. Higher values create larger segments. sigma : float Width (standard deviation) of Gaussian kernel for pre-processing. Higher values give more smoothing. min_size : int Minimum component size. Smaller components are merged with neighboring larger components. **kwargs : dict Additional parameters passed to skimage.segmentation.felzenszwalb()
Source code in nickyspatial/core/segmentation.py
execute(image_data=None, transform=None, crs=None, raster_path=None, target_crs=None, layer_manager=None, layer_name=None)
¶
Perform Felzenszwalb segmentation and create a layer with the results.
Source code in nickyspatial/core/segmentation.py
RegularGridSegmentation
¶
Bases: BaseSegmentation
Implementation of regular grid segmentation algorithm.
This algorithm divides the image into regular rectangular segments of specified dimensions, creating a uniform grid pattern across the entire image.
Source code in nickyspatial/core/segmentation.py
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 |
|
__init__(grid_size=(10, 10), overlap=0, boundary_handling='pad')
¶
Initialize the regular grid segmentation algorithm.
Parameters:¶
grid_size : tuple of int Size of each grid cell (height, width) in pixels. For example, (10, 10) creates 10x10 pixel squares. overlap : int, optional Number of pixels to overlap between adjacent segments. Default is 0 (no overlap). boundary_handling : str, optional How to handle boundary segments that don't fit exactly: - 'pad': Pad the image to fit complete grid cells - 'truncate': Allow partial segments at boundaries - 'stretch': Stretch boundary segments to fill remaining space
Source code in nickyspatial/core/segmentation.py
execute(image_data=None, transform=None, crs=None, raster_path=None, target_crs=None, layer_manager=None, layer_name=None)
¶
Perform regular grid segmentation and create a layer with the results.
Source code in nickyspatial/core/segmentation.py
SlicSegmentation
¶
Bases: BaseSegmentation
Implementation of Multiresolution segmentation algorithm.
This algorithm segments an image using a bottom-up region-growing approach that optimizes the homogeneity of pixel values within segments while considering shape compactness.
Source code in nickyspatial/core/segmentation.py
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 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 |
|
__init__(scale=15, compactness=0.6, **kwargs)
¶
Initialize the segmentation algorithm.
Parameters:¶
scale : float Scale parameter that influences the size of the segments. Higher values create larger segments. shape : float, range [0, 1] Weight of shape criterion vs. color criterion. Higher values give more weight to shape. compactness : float, range [0, 1] Weight of compactness criterion vs. smoothness criterion. Higher values create more compact segments. **kwargs : dict Additional parameters passed to skimage.segmentation.slic()
Source code in nickyspatial/core/segmentation.py
execute(image_data=None, transform=None, crs=None, raster_path=None, target_crs=None, layer_manager=None, layer_name=None)
¶
Perform segmentation and create a layer with the results.
Parameters:¶
image_data : numpy.ndarray, optional Array with raster data values (bands, height, width). If not provided, must specify raster_path. transform : affine.Affine, optional Affine transformation for the raster. If not provided, will be extracted from raster_path. crs : rasterio.crs.CRS, optional Coordinate reference system. If not provided, will be extracted from raster_path. raster_path : str, optional Path to raster file. If provided, image_data, transform, and crs will be extracted automatically. target_crs : str or rasterio.crs.CRS, optional Target CRS for the output. If different from input CRS, automatic reprojection will be performed. layer_manager : LayerManager, optional Layer manager to add the result layer to layer_name : str, optional Name for the result layer
Returns:¶
layer : Layer Layer containing the segmentation results
Source code in nickyspatial/core/segmentation.py
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 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 |
|
WatershedSegmentation
¶
Bases: BaseSegmentation
Implementation of watershed segmentation algorithm using regular grid seeding.
The watershed algorithm treats the image as a topographic surface where pixel intensities represent elevation. It finds watershed lines that separate different catchment basins, effectively segmenting the image into distinct regions.
Source code in nickyspatial/core/segmentation.py
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 |
|
__init__(n_points=468, compactness=0, watershed_line=False, preprocessing='sobel', mask=None, **kwargs)
¶
Initialize the watershed segmentation algorithm.
Parameters:¶
n_points : int Number of seed points to generate using regular grid. Higher values create more segments. compactness : float, optional Use compact watershed with given compactness parameter. Higher values result in more regularly-shaped watershed basins. watershed_line : bool, optional If watershed_line is True, a one-pixel wide line separates the regions obtained by the watershed algorithm. The line has the label 0. preprocessing : str, optional Method for preprocessing the image before watershed segmentation. Options: 'sobel', 'prewitt', 'scharr' mask : ndarray of bools or 0s and 1s, optional Array of same shape as image. Only points at which mask == True will be labeled. **kwargs : dict Additional parameters passed to watershed function
Source code in nickyspatial/core/segmentation.py
execute(image_data=None, transform=None, crs=None, raster_path=None, target_crs=None, layer_manager=None, layer_name=None)
¶
Perform watershed segmentation and create a layer with the results.
Source code in nickyspatial/core/segmentation.py
nickyspatial.filters
¶
The filters package provides modules for applying transformations to raster data.
It includes spatial filters (e.g., smoothing) as well as spectral filters (e.g., band math). Main idea is to further manipulate the objects such as merging segments or applying pre-defined rules to filter objects based on their attributes.
Implements spatial operations like smoothing and morphological transformations.
These filters can modify the geometry or arrangement of pixel values to enhance or simplify data for object analysis. The functions here include smoothing boundaries, merging small segments, and selecting segments based on area. These operations are essential for preparing data for object-based image analysis, especially in remote sensing applications. The functions are designed to work with raster data and can be applied to layers created from segmentation algorithms.
merge_small_segments(source_layer, min_size, attribute='area_pixels', layer_manager=None, layer_name=None)
¶
Merge small segments with their largest neighbor.
Parameters:¶
source_layer : Layer Source layer with segments to merge min_size : float Minimum segment size threshold attribute : str Attribute to use for size comparison layer_manager : LayerManager, optional Layer manager to add the result layer to layer_name : str, optional Name for the result layer
Returns:¶
result_layer : Layer Layer with merged segments
Source code in nickyspatial/filters/spatial.py
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 |
|
select_by_area(source_layer, min_area=None, max_area=None, area_column='area_units', layer_manager=None, layer_name=None)
¶
Select segments based on area.
Parameters:¶
source_layer : Layer Source layer with segments to filter min_area : float, optional Minimum area threshold max_area : float, optional Maximum area threshold area_column : str Column containing area values layer_manager : LayerManager, optional Layer manager to add the result layer to layer_name : str, optional Name for the result layer
Returns:¶
result_layer : Layer Layer with filtered segments
Source code in nickyspatial/filters/spatial.py
smooth_boundaries(source_layer, iterations=1, layer_manager=None, layer_name=None)
¶
Smooth segment boundaries by applying morphological operations.
Parameters:¶
source_layer : Layer Source layer with segments to smooth iterations : int Number of smoothing iterations to apply layer_manager : LayerManager, optional Layer manager to add the result layer to layer_name : str, optional Name for the result layer
Returns:¶
result_layer : Layer Layer with smoothed segment boundaries
Source code in nickyspatial/filters/spatial.py
Performs spectral-based manipulations of imagery, including band arithmetic and transformations.
It supports generating new spectral bands or combinations to highlight specific features. It also includes functions for enhancing contrast and applying spectral filters based on mathematical expressions. This module is designed to work with raster . The functions here include contrast enhancement, spectral filtering, and band arithmetic. Not a great fan of these but might be handy sometime
enhance_contrast(source_layer, percentile_min=2, percentile_max=98, layer_manager=None, layer_name=None)
¶
Enhance contrast in source layer raster data.
Parameters:¶
source_layer : Layer Source layer with raster data percentile_min : float Lower percentile for contrast stretching percentile_max : float Upper percentile for contrast stretching layer_manager : LayerManager, optional Layer manager to add the result layer to layer_name : str, optional Name for the result layer
Returns:¶
result_layer : Layer Layer with enhanced contrast
Source code in nickyspatial/filters/spectral.py
spectral_filter(source_layer, expression, layer_manager=None, layer_name=None)
¶
Apply a spectral filter based on a mathematical expression.
Parameters:¶
source_layer : Layer Source layer with segment statistics expression : str Mathematical expression to apply (e.g., "NDVI > 0.5") layer_manager : LayerManager, optional Layer manager to add the result layer to layer_name : str, optional Name for the result layer
Returns:¶
result_layer : Layer Layer with filtered segments
Source code in nickyspatial/filters/spectral.py
nickyspatial.io
¶
The io package contains modules for reading and writing both raster and vector data.
It abstracts file operations and coordinate system handling to facilitate I/O tasks.
Handles raster input and output operations, including reading and saving multi-band images.
Functions in this module may also provide metadata parsing and coordinate transform tools.
layer_to_raster(layer, output_path, column=None, nodata=0)
¶
Save a layer to a raster file.
Parameters:¶
layer : Layer Layer to save output_path : str Path to the output raster file column : str, optional Column to rasterize (if saving from vector objects) nodata : int or float, optional No data value
Source code in nickyspatial/io/raster.py
read_raster(raster_path)
¶
Read a raster file and return its data, transform, and CRS.
Parameters:¶
raster_path : str Path to the raster file
Returns:¶
image_data : numpy.ndarray Array with raster data values transform : affine.Affine Affine transformation for the raster crs : rasterio.crs.CRS Coordinate reference system
Source code in nickyspatial/io/raster.py
write_raster(output_path, data, transform, crs, nodata=None)
¶
Write raster data to a file.
Parameters:¶
output_path : str Path to the output raster file data : numpy.ndarray Array with raster data values transform : affine.Affine Affine transformation for the raster crs : rasterio.crs.CRS Coordinate reference system nodata : int or float, optional No data value
Source code in nickyspatial/io/raster.py
Manages vector data I/O, supporting formats like Shapefile and GeoJSON.
This module typically offers utilities for handling attributes, geometries, and coordinate reference systems.
layer_to_vector(layer, output_path)
¶
Save a layer's objects to a vector file.
Parameters:¶
layer : Layer Layer to save output_path : str Path to the output vector file
Source code in nickyspatial/io/vector.py
read_vector(vector_path)
¶
write_vector(gdf, output_path)
¶
Write a GeoDataFrame to a vector file.
Parameters:¶
gdf : geopandas.GeoDataFrame GeoDataFrame to write output_path : str Path to the output vector file
Source code in nickyspatial/io/vector.py
nickyspatial.stats
¶
The stats package includes modules for calculating statistical metrics on objects.
This is to mimic the stats module in ecognition because they will be necessary in order to apply rules later on and extremely essential to work with objects
Basic statistics for layers in NickySpatial.
attach_basic_stats(layer, column, prefix=None)
¶
Attach basic statistics for a column to a layer.
Parameters:¶
layer : Layer Layer to attach statistics to column : str Column to calculate statistics for prefix : str, optional Prefix for result names
Returns:¶
stats : dict Dictionary with calculated statistics
Source code in nickyspatial/stats/basic.py
attach_class_distribution(layer, class_column='classification')
¶
Calculate the distribution of classes in a layer.
Parameters:¶
layer : Layer Layer to analyze class_column : str Column containing class values
Returns:¶
distribution : dict Dictionary with class counts and percentages
Source code in nickyspatial/stats/basic.py
attach_count(layer, class_column='classification', class_value=None)
¶
Count objects in a layer, optionally filtered by class.
Parameters:¶
layer : Layer Layer to count objects in class_column : str Column containing class values class_value : str, optional Class value to filter by
Returns:¶
count : int Number of objects
Source code in nickyspatial/stats/basic.py
Spatial statistics for layers in NickySpatial.
attach_area_stats(layer, area_column='area_units', by_class=None)
¶
Calculate area statistics for objects in a layer.
Parameters:¶
layer : Layer Layer to calculate statistics for area_column : str Column containing area values by_class : str, optional Column to group by (e.g., 'classification')
Returns:¶
stats : dict Dictionary with area statistics
Source code in nickyspatial/stats/spatial.py
attach_neighbor_stats(layer)
¶
Calculate neighborhood statistics for objects in a layer.
Parameters:¶
layer : Layer Layer to calculate statistics for
Returns:¶
stats : dict Dictionary with neighborhood statistics
Source code in nickyspatial/stats/spatial.py
attach_shape_metrics(layer)
¶
Calculate shape metrics for objects in a layer.
Parameters:¶
layer : Layer Layer to calculate metrics for
Returns:¶
metrics : dict Dictionary with shape metrics
Source code in nickyspatial/stats/spatial.py
Spectral indices calculation module.
SpectralIndexCalculator
¶
A spectral index calculator that supports custom formulas.
Supports predefined indices from the awesome-spectral-indices catalogue.
Source code in nickyspatial/stats/spectral.py
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 |
|
__init__()
¶
Initialize the calculator with predefined indices.
Source code in nickyspatial/stats/spectral.py
add_custom_index(name, formula, description='', reference='')
¶
Add a custom index to the global predefined indices.
Parameters:¶
name : str Name of the index formula : str Mathematical formula description : str, optional Description of the index reference : str, optional Reference/citation for the index
Source code in nickyspatial/stats/spectral.py
attach_ndvi(layer, nir_column='NIR_mean', red_column='Red_mean', output_column='NDVI')
¶
Calculate NDVI (Normalized Difference Vegetation Index) for objects in a layer.
Parameters:¶
layer : Layer Layer to calculate NDVI for nir_column : str Column containing NIR band values red_column : str Column containing Red band values output_column : str Column to store NDVI values
Returns:¶
ndvi_stats : dict Dictionary with NDVI statistics
Source code in nickyspatial/stats/spectral.py
attach_spectral_index(layer, index_name, formula=None, bands=None, output_column=None)
¶
Calculate a single spectral index using a custom or predefined formula.
This function is designed to work with Layer.attach_function().
Parameters:¶
layer : Layer Layer object with objects DataFrame index_name : str Name of the index to calculate formula : str, optional Custom formula to use. If None, uses predefined formula for index_name bands : dict, optional Dictionary mapping band names to column names output_column : str, optional Name of output column. If None, uses index_name
Returns:¶
dict Dictionary with index statistics and metadata
Source code in nickyspatial/stats/spectral.py
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 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 |
|
attach_spectral_indices(layer, bands=None)
¶
Calculate multiple spectral indices for objects in a layer.
Parameters:¶
layer : Layer Layer to calculate indices for bands : dict, optional Dictionary mapping band names to column names
Returns:¶
indices : dict Dictionary with calculated indices
Source code in nickyspatial/stats/spectral.py
nickyspatial.utils
¶
This modules contains utility functions for handling attributes, geometries, and coordinate reference systems.
nickyspatial.viz
¶
Alrighty , let's get this visualization party started!
No matter what you do you need to see it and present it , this is the module for it to contain all code about visualizaing the layers , object rule results etc.
Visualization functions for plotting histograms, statistics, and scatter plots.
plot_histogram(layer, attribute, bins=20, figsize=(10, 6), by_class=None)
¶
Plot a histogram of attribute values.
Parameters:¶
layer : Layer Layer containing data attribute : str Attribute to plot bins : int Number of bins figsize : tuple Figure size by_class : str, optional Column to group by (e.g., 'classification')
Returns:¶
fig : matplotlib.figure.Figure Figure object
Source code in nickyspatial/viz/charts.py
plot_statistics(layer, stats_dict, figsize=(12, 8), kind='bar', y_log=False)
¶
Plot statistics from a statistics dictionary.
Parameters:¶
layer : Layer Layer the statistics are calculated for stats_dict : dict Dictionary with statistics (from attach_* functions) figsize : tuple Figure size kind : str Plot type: 'bar', 'line', or 'pie' y_log : bool Whether to use logarithmic scale for y-axis
Returns:¶
fig : matplotlib.figure.Figure Figure object
Source code in nickyspatial/viz/charts.py
plot_training_history(history)
¶
Plot (training and validation) loss and accuracy curves from a Keras(CNN) training history.
This function visualizes the model's performance over epochs by plotting: - Training and validation loss - Training and validation accuracy
Parameters¶
history : keras.callbacks.History
History object returned by model.fit()
, containing loss and accuracy values
for each epoch.
Returns:¶
matplotlib.pyplot The pyplot module with the generated figure, allowing further modification or saving.
Source code in nickyspatial/viz/charts.py
Functions to create maps and visualize layers.
plot_classification(layer, class_field='classification', figsize=(12, 10), legend=True, class_color=None)
¶
Plot classified segments with different colors for each class.
Source code in nickyspatial/viz/maps.py
plot_comparison(before_layer, after_layer, attribute=None, class_field=None, figsize=(16, 8), title=None)
¶
Plot before and after views of layers for comparison.
Source code in nickyspatial/viz/maps.py
plot_layer(layer, image_data=None, attribute=None, title=None, rgb_bands=(2, 1, 0), figsize=(12, 10), cmap='viridis', show_boundaries=False)
¶
Plot a layer, optionally with an attribute or image backdrop.
Source code in nickyspatial/viz/maps.py
plot_layer_interactive(layer, image_data=None, figsize=(10, 8))
¶
Interactive plot of a layer with widgets and working click.
Source code in nickyspatial/viz/maps.py
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 |
|
plot_layer_interactive_plotly(layer, image_data, rgb_bands=(0, 1, 2), show_boundaries=True, figsize=(800, 400))
¶
Display an interactive RGB image with segment boundaries and hoverable segment IDs using Plotly.
Run in google collab as well.
Parameters:¶
layer : object
An object with a .raster
attribute representing the labeled segmentation layer
(e.g., output from a segmentation algorithm, such as SLIC).
image_data : image data to be visualized.
rgb_bands : tuple of int, optional
Tuple of three integers specifying which bands to use for the RGB composite (default is (0, 1, 2)).
show_boundaries : bool, optional
Whether to overlay the segment boundaries on the RGB image (default is True).
figsize : tuple of int, optional
Tuple specifying the width and height of the interactive Plotly figure in pixels (default is (800, 400)).
Returns:¶
None The function displays the interactive plot directly in the output cell in a Jupyter Notebook.
Notes:¶
- Segment boundaries are drawn using
skimage.segmentation.mark_boundaries
. - Hovering over the image displays the segment ID from
layer.raster
.
Source code in nickyspatial/viz/maps.py
plot_sample(layer, image_data=None, transform=None, rgb_bands=None, class_field='classification', figsize=(8, 6), class_color=None, legend=True)
¶
Plot classified segments on top of RGB or grayscale image data.
Parameters: - layer: Layer object with .objects (GeoDataFrame) - image_data: 3D numpy array (bands, height, width) - transform: Affine transform for the image (needed to compute extent) - red_band, green_band, blue_band: indices for RGB bands
Source code in nickyspatial/viz/maps.py
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 |
|
plot_subplots_classification(layer, class_field='classification', figsize=(12, 10), legend=True, class_color=None, ax=None, title=None)
¶
Plot classified segments with different colors for each class.
layer : figsize: class_clor: ax : ax instance of matplotlib Axes to plot on. title : str, optional Title for the plot. If None, defaults to "Classification Map".
Source code in nickyspatial/viz/maps.py
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 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 |
|