|
| 1 | +# Importing necessary libraries |
| 2 | +import numpy as np |
| 3 | +from PIL import Image |
| 4 | +import matplotlib.pyplot as plt |
| 5 | +from typing import List |
| 6 | + |
| 7 | +def segment_image(image: np.ndarray, thresholds: List[int]) -> np.ndarray: |
| 8 | + """ |
| 9 | + Performs image segmentation based on intensity thresholds. |
| 10 | + Args: |
| 11 | + image (np.ndarray): Input grayscale image as a 2D array. |
| 12 | + thresholds (List[int]): A list of intensity thresholds to define segments. |
| 13 | + Returns: |
| 14 | + np.ndarray: A labeled 2D array where each region corresponds to a threshold range. |
| 15 | + Example: |
| 16 | + >>> img = np.array([[80, 120, 180], [40, 90, 150], [20, 60, 100]]) |
| 17 | + >>> segment_image(img, [50, 100, 150]) |
| 18 | + array([[1, 2, 3], |
| 19 | + [0, 1, 2], |
| 20 | + [0, 0, 1]]) |
| 21 | + """ |
| 22 | + # Initialize an empty array to store segment labels |
| 23 | + segmented = np.zeros_like(image, dtype=np.int32) |
| 24 | + |
| 25 | + # Iterate over thresholds and label pixels in corresponding intensity ranges |
| 26 | + for i, threshold in enumerate(thresholds): |
| 27 | + segmented[image > threshold] = i + 1 |
| 28 | + |
| 29 | + return segmented |
| 30 | + |
| 31 | +if __name__ == "__main__": |
| 32 | + # Path to the image file |
| 33 | + image_path = "path_to_image" # Replace with the path to your local image file |
| 34 | + |
| 35 | + # Load and preprocess the image |
| 36 | + original_image = Image.open(image_path).convert("L") # Convert image to grayscale |
| 37 | + image_array = np.array(original_image) # Convert image to a numpy array |
| 38 | + |
| 39 | + # Specify intensity thresholds for segmentation |
| 40 | + thresholds = [50, 100, 150, 200] # Define your desired thresholds |
| 41 | + |
| 42 | + # Apply segmentation to the image |
| 43 | + segmented_image = segment_image(image_array, thresholds) |
| 44 | + |
| 45 | + # Visualize the results |
| 46 | + plt.figure(figsize=(12, 6)) |
| 47 | + |
| 48 | + # Display the original image |
| 49 | + plt.subplot(1, 2, 1) |
| 50 | + plt.title("Original Grayscale Image") |
| 51 | + plt.imshow(image_array, cmap="gray") |
| 52 | + plt.axis("off") |
| 53 | + |
| 54 | + # Display the segmented image with labeled regions |
| 55 | + plt.subplot(1, 2, 2) |
| 56 | + plt.title("Segmented Image") |
| 57 | + plt.imshow(segmented_image, cmap="tab20") # Use a colormap for better distinction |
| 58 | + plt.axis("off") |
| 59 | + |
| 60 | + # Show the plots |
| 61 | + plt.tight_layout() |
| 62 | + plt.show() |
0 commit comments