Morphological operations (erosion, dilation) in SciPy - Time & Space Complexity
We want to understand how the time needed to perform morphological operations changes as the image size grows.
How does the processing time increase when the input image gets bigger?
Analyze the time complexity of the following code snippet.
import numpy as np
from scipy.ndimage import binary_erosion, binary_dilation
image = np.random.randint(0, 2, (n, n), dtype=bool)
structure = np.ones((3, 3), dtype=bool)
eroded = binary_erosion(image, structure=structure)
dilated = binary_dilation(image, structure=structure)
This code applies erosion and dilation on a binary image using a 3x3 structuring element.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Each pixel in the image is visited and compared with its neighbors defined by the structuring element.
- How many times: Once for each pixel in the image, so n × n times for an n by n image.
As the image size grows, the number of pixels to process grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 100 (10×10) |
| 100 | 10,000 (100×100) |
| 1000 | 1,000,000 (1000×1000) |
Pattern observation: The operations grow roughly with the square of the image dimension because each pixel is processed once.
Time Complexity: O(n²)
This means the time to complete erosion or dilation grows proportionally to the total number of pixels in the image.
[X] Wrong: "Morphological operations take constant time regardless of image size because they just look at neighbors."
[OK] Correct: Even though each pixel looks at neighbors, every pixel must be processed, so the total work grows with the number of pixels.
Understanding how image size affects processing time helps you explain performance in real projects involving image analysis or computer vision.
"What if we used a larger structuring element, like 5x5 instead of 3x3? How would the time complexity change?"