Label return labels read the binary imageimage imread
Component Labeling Assignment Answers
Question:
Write OpenCV code to perform the following tasks:
intensity values within the set V, where V={min-max}, to determine pixel
connectivity. The values of min and max are user-input parameters.
Please submit your source code, and adhere to the following regulations.
Only Python programming language can be used, in conjunction with
Component Labeling Answer and Explanation
Task 1: Implement the component labeling algorithm
This task involves labeling connected components in a binary image using 4-connectivity.
label = 1
labels = np.zeros_like(image, dtype=int)
def is_valid(x, y):
return 0 <= x < rows and 0 <= y < cols
for dx, dy in connectivity:
nx, ny = cx + dx, cy + dy
for i in range(rows):
for j in range(cols):
return labels
# Read the binary image
labeled_image = label_components_4_connectivity(binary_image)
# Save the labeled image
label = 1
labels = np.zeros_like(image, dtype=int)
def is_valid(x, y):
return 0 <= x < rows and 0 <= y < cols
for dx, dy in connectivity:
nx, ny = cx + dx, cy + dy
for i in range(rows):
for j in range(cols):
return labels
# Label the components using 8-connectivity
def label_components_intensity_range(image, min_val, max_val):
# Initialize label and label matrix
# Get image dimensions
rows, cols = image.shape
while queue:
cx, cy = queue.pop(0)
queue.append((nx, ny))
# Label the components
bfs(i, j)
label += 1
min_val = 100 # user input
max_val = 200 # user input
Task 4: Implement the size filter algorithm
def size_filter(image, min_size):
size_mask = {label: (counts[i] >= min_size) for i, label in enumerate(unique)}
# Apply the size filter
min_size = 500 # user input
# Filter the components by size
Combining all tasks, here's the full code:
import cv2
connectivity = [(0, 1), (1, 0), (0, -1), (-1, 0)]
rows, cols = image.shape
while queue:
cx, cy = queue.pop(0)
queue.append((nx, ny))
for i in range(rows):
label += 1
return labels
rows, cols = image.shape
def is_valid(x, y):
cx, cy = queue.pop(0)
for dx, dy in connectivity:
for i in range(rows):
for j in range(cols):
return labels
def label_components_intensity_range(image, min_val, max_val):
def is_valid(x, y):
return 0 <= x < rows and 0 <= y < cols
for dx, dy in connectivity:
nx, ny = cx + dx, cy + dy
for j in range(cols):
if min_val <= image[i, j] <= max_val and labels[i, j] == 0:
def size_filter(image, min_size):
unique, counts = np.unique(image, return_counts=True)
_, binary_image = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)
labeled_image_4 = label_components_4_connectivity(binary_image)
min_val = 100
max_val = 200
cv2.imwrite('filtered_labeled_image.png', filtered_labeled_image)
This code covers all the tasks as specified. Ensure you have the necessary images (`binary_image.png` and `grayscale_image.png`) in the same directory as your script, and modify the paths as needed.