- SciPy - Home
- SciPy - Introduction
- SciPy - Environment Setup
- SciPy - Basic Functionality
- SciPy - Relationship with NumPy
- SciPy Clusters
- SciPy - Clusters
- SciPy - Hierarchical Clustering
- SciPy - K-means Clustering
- SciPy - Distance Metrics
- SciPy Constants
- SciPy - Constants
- SciPy - Mathematical Constants
- SciPy - Physical Constants
- SciPy - Unit Conversion
- SciPy - Astronomical Constants
- SciPy - Fourier Transforms
- SciPy - FFTpack
- SciPy - Discrete Fourier Transform (DFT)
- SciPy - Fast Fourier Transform (FFT)
- SciPy Integration Equations
- SciPy - Integrate Module
- SciPy - Single Integration
- SciPy - Double Integration
- SciPy - Triple Integration
- SciPy - Multiple Integration
- SciPy Differential Equations
- SciPy - Differential Equations
- SciPy - Integration of Stochastic Differential Equations
- SciPy - Integration of Ordinary Differential Equations
- SciPy - Discontinuous Functions
- SciPy - Oscillatory Functions
- SciPy - Partial Differential Equations
- SciPy Interpolation
- SciPy - Interpolate
- SciPy - Linear 1-D Interpolation
- SciPy - Polynomial 1-D Interpolation
- SciPy - Spline 1-D Interpolation
- SciPy - Grid Data Multi-Dimensional Interpolation
- SciPy - RBF Multi-Dimensional Interpolation
- SciPy - Polynomial & Spline Interpolation
- SciPy Curve Fitting
- SciPy - Curve Fitting
- SciPy - Linear Curve Fitting
- SciPy - Non-Linear Curve Fitting
- SciPy - Input & Output
- SciPy - Input & Output
- SciPy - Reading & Writing Files
- SciPy - Working with Different File Formats
- SciPy - Efficient Data Storage with HDF5
- SciPy - Data Serialization
- SciPy Linear Algebra
- SciPy - Linalg
- SciPy - Matrix Creation & Basic Operations
- SciPy - Matrix LU Decomposition
- SciPy - Matrix QU Decomposition
- SciPy - Singular Value Decomposition
- SciPy - Cholesky Decomposition
- SciPy - Solving Linear Systems
- SciPy - Eigenvalues & Eigenvectors
- SciPy Image Processing
- SciPy - Ndimage
- SciPy - Reading & Writing Images
- SciPy - Image Transformation
- SciPy - Filtering & Edge Detection
- SciPy - Top Hat Filters
- SciPy - Morphological Filters
- SciPy - Low Pass Filters
- SciPy - High Pass Filters
- SciPy - Bilateral Filter
- SciPy - Median Filter
- SciPy - Non - Linear Filters in Image Processing
- SciPy - High Boost Filter
- SciPy - Laplacian Filter
- SciPy - Morphological Operations
- SciPy - Image Segmentation
- SciPy - Thresholding in Image Segmentation
- SciPy - Region-Based Segmentation
- SciPy - Connected Component Labeling
- SciPy Optimize
- SciPy - Optimize
- SciPy - Special Matrices & Functions
- SciPy - Unconstrained Optimization
- SciPy - Constrained Optimization
- SciPy - Matrix Norms
- SciPy - Sparse Matrix
- SciPy - Frobenius Norm
- SciPy - Spectral Norm
- SciPy Condition Numbers
- SciPy - Condition Numbers
- SciPy - Linear Least Squares
- SciPy - Non-Linear Least Squares
- SciPy - Finding Roots of Scalar Functions
- SciPy - Finding Roots of Multivariate Functions
- SciPy - Signal Processing
- SciPy - Signal Filtering & Smoothing
- SciPy - Short-Time Fourier Transform
- SciPy - Wavelet Transform
- SciPy - Continuous Wavelet Transform
- SciPy - Discrete Wavelet Transform
- SciPy - Wavelet Packet Transform
- SciPy - Multi-Resolution Analysis
- SciPy - Stationary Wavelet Transform
- SciPy - Statistical Functions
- SciPy - Stats
- SciPy - Descriptive Statistics
- SciPy - Continuous Probability Distributions
- SciPy - Discrete Probability Distributions
- SciPy - Statistical Tests & Inference
- SciPy - Generating Random Samples
- SciPy - Kaplan-Meier Estimator Survival Analysis
- SciPy - Cox Proportional Hazards Model Survival Analysis
- SciPy Spatial Data
- SciPy - Spatial
- SciPy - Special Functions
- SciPy - Special Package
- SciPy Advanced Topics
- SciPy - CSGraph
- SciPy - ODR
- SciPy Useful Resources
- SciPy - Reference
- SciPy - Quick Guide
- SciPy - Cheatsheet
- SciPy - Useful Resources
- SciPy - Discussion
SciPy - ndimage.generate_binary_structure() Function
The scipy.ndimage.generate_binary_structure() is a function in the SciPy library which is used to create a structuring element for binary morphological operations. It generates a multi-dimensional array where True values represent the shape of the structuring element.
This function takes two parameters namely, rank which specifies the number of dimensions and connectivity which determines the extent of connectivity with 1 for a cross shape or 2 for a full neighborhood.
Structuring elements are essential for operations such as dilation, erosion, opening and closing in image processing. This function provides flexibility for defining shapes in both 2D and higher-dimensional spaces.
Syntax
Following is the syntax of the function scipy.ndimage.generate_binary_structure() to create Structuring element −
scipy.ndimage.generate_binary_structure(rank, connectivity)
Parameters
Following are the parameters of the scipy.ndimage.generate_binary_structure() function −
- rank(int): The dimensionality of the structuring element such as 2 for 2D, 3 for 3D, etc.
- connectivity(int): This parameter determines the type of connectivity or neighborhood. 1 includes only the nearest neighbors in each dimension i.e., cross-shaped neighborhood in 2D and 2 includes diagonal neighbors i.e., full square or cube neighborhood in 2D or 3D.
Return Value
The scipy.ndimage.generate_binary_structure() function returns a binary structuring element represented as a NumPy array of boolean values.
2D Structuring Element with Connectivity 2
A 2D structuring element with connectivity 2 includes all the pixels surrounding the central pixel by forming a square shape which is also called full connectivity. This means that the central pixel is connected to its 8 neighbors. Here's an example of creating and using a 2D structuring element with connectivity 2 −
from scipy.ndimage import generate_binary_structure
# Create a 2D structuring element with connectivity 2
struct_2d_full = generate_binary_structure(rank=2, connectivity=2)
# Print the structuring element
print("2D Structuring Element (Connectivity 2):\n", struct_2d_full)
Here is the output of the function scipy.ndimage.generate_binary_structure() which is used to create a 2D structuring element −
2D Structuring Element (Connectivity 2): [[ True True True] [ True True True] [ True True True]]
Enlarging Structuring Elements
In morphological operations, enlarging a structuring element can make the effect of dilation, erosion or other operations more pronounced. We can enlarge a structuring element using scipy.ndimage.iterate_structure(). This function repeats the structuring element dilation multiple times, effectively increasing its size.
Following is the example which uses the scipy.ndimage.iterate_structure() function along with the scipy.ndimage.generate_binary_structure() function for enlarging structuring element −
from scipy.ndimage import generate_binary_structure, iterate_structure
# Create a 2D cross-shaped structuring element
struct_2d = generate_binary_structure(rank=2, connectivity=1)
print("Original Structuring Element:\n", struct_2d)
# Enlarge the structuring element by 2 iterations
enlarged_struct = iterate_structure(struct_2d, iterations=2)
print("Enlarged Structuring Element (2 iterations):\n", enlarged_struct)
Here is the output of the enlarging the structuring element −
2D Structuring Element (Connectivity 2): [[ True True True] [ True True True] [ True True True]]
Closing with a Structuring Element
Using a structuring element with closing involves applying the closing operation on a binary image. Closing is a morphological operation that fills small holes and gaps in the foreground while preserving the overall shape. It consists of a dilation followed by an erosion.
Following is the example which uses the scipy.ndimage.generate_binary_structure() function in Closing −
from scipy.ndimage import binary_closing, generate_binary_structure
import numpy as np
import matplotlib.pyplot as plt
# Create a binary image with a small gap
image_with_gaps = np.zeros((10, 10), dtype=int)
image_with_gaps[4:7, 4:7] = 1 # Square in the center
image_with_gaps[5, 5] = 0 # A small hole
image_with_gaps[6, 4] = 0 # Gap in the square
# Define a 2D structuring element with connectivity 2 (full connectivity)
struct_2d = generate_binary_structure(rank=2, connectivity=2)
# Apply the closing operation
closed_image = binary_closing(image_with_gaps, structure=struct_2d)
# Plot the results
plt.figure(figsize=(15, 5))
# Original image
plt.subplot(1, 3, 1)
plt.title("Original Image with Gaps")
plt.imshow(image_with_gaps, cmap='gray')
plt.axis('off')
# Structuring Element
plt.subplot(1, 3, 2)
plt.title("Structuring Element")
plt.imshow(struct_2d, cmap='gray')
plt.axis('off')
# Closed Image
plt.subplot(1, 3, 3)
plt.title("Closed Image")
plt.imshow(closed_image, cmap='gray')
plt.axis('off')
plt.show()
Here is the output of the structuring element used in Closing −