Complete the code to import the connected components function from scipy.ndimage.
from scipy.ndimage import [1]
The function label from scipy.ndimage is used to find connected components in an array.
Complete the code to create a binary 2D numpy array named 'image' with a 3x3 block of ones in the center.
import numpy as np image = np.zeros((7, 7), dtype=int) image[[1]] = 1
The slice 2:5, 2:5 selects a 3x3 block in the center of a 7x7 array.
Fix the error in the code to label connected components in 'image' using 4-connectivity.
labeled_array, num_features = label(image, [1]=1)
The correct parameter name is connectivity which defines the neighborhood connectivity.
Fill both blanks to create a structuring element for 8-connectivity and label the image accordingly.
structure = np.array([[[1], [2], [1]], [[2], 1, [2]], [[1], [2], [1]]]) labeled_array, num_features = label(image, structure=structure)
For 8-connectivity, the structuring element uses 1s for all neighbors including diagonals and the center.
Fill all three blanks to create a dictionary comprehension that maps each label to the count of pixels in that component, excluding background (label 0).
counts = {label: (labeled_array == label).[1]() for label in range(1, [2] + [3])}The sum() counts pixels for each label. The range goes from 1 to num_features + 1 to exclude background label 0.