AI-driven Image Segmentation Python, AI

👤 Sharing: AI
```python
import cv2
import numpy as np
from sklearn.cluster import KMeans

def segment_image_kmeans(image_path, n_clusters=5, compactness=100.0, connectivity=8):
    """
    Segments an image using K-Means clustering on pixel colors.

    Args:
        image_path (str): Path to the image file.
        n_clusters (int):  The number of clusters to form, i.e., the number of segments.
        compactness (float): Not used in this k-means implementation, kept for API consistency.
        connectivity (int): Not used in this k-means implementation, kept for API consistency.

    Returns:
        numpy.ndarray: The segmented image.
    """
    img = cv2.imread(image_path)
    if img is None:
        raise ValueError(f"Could not read image at {image_path}")

    # Reshape the image to be a list of pixels
    pixels = img.reshape((-1, 3))

    # Use k-means to cluster the pixel colors
    kmeans = KMeans(n_clusters=n_clusters, random_state=0, n_init='auto')
    cluster_labels = kmeans.fit_predict(pixels)

    # Replace each pixel with its cluster center color
    segmented_pixels = kmeans.cluster_centers_[cluster_labels]
    segmented_img = segmented_pixels.reshape(img.shape).astype(np.uint8)

    return segmented_img


def segment_image_watershed(image_path):
    """
    Segments an image using the Watershed algorithm.

    Args:
        image_path (str): Path to the image file.

    Returns:
        numpy.ndarray: The segmented image.
    """
    img = cv2.imread(image_path)
    if img is None:
        raise ValueError(f"Could not read image at {image_path}")

    # Preprocessing
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

    # Noise removal
    kernel = np.ones((3, 3), np.uint8)
    opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)

    # Sure background area
    sure_bg = cv2.dilate(opening, kernel, iterations=3)

    # Finding sure foreground area
    dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
    ret, sure_fg = cv2.threshold(dist_transform, 0.7 * dist_transform.max(), 255, 0)
    sure_fg = np.uint8(sure_fg)

    # Finding unknown region
    unknown = cv2.subtract(sure_bg, sure_fg)

    # Marker labelling
    ret, markers = cv2.connectedComponents(sure_fg)

    # Add one to all labels so that sure background is not 0, but 1
    markers = markers + 1

    # Now, mark the region of unknown with zero
    markers[unknown == 255] = 0

    # Watershed algorithm
    markers = cv2.watershed(img, markers)
    img[markers == -1] = [255, 0, 0]  # Mark watershed lines with blue

    return img


def segment_image_simple_thresholding(image_path, threshold_value=127, max_value=255, threshold_type=cv2.THRESH_BINARY):
    """
    Segments an image using simple thresholding.

    Args:
        image_path (str): Path to the image file.
        threshold_value (int):  Threshold value used to classify pixel values.
        max_value (int):  Maximum value to be assigned to pixel values exceeding the threshold.
        threshold_type (int): Type of thresholding to apply (e.g., cv2.THRESH_BINARY, cv2.THRESH_BINARY_INV).

    Returns:
        numpy.ndarray: The segmented image.
    """

    img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) # Load in grayscale
    if img is None:
        raise ValueError(f"Could not read image at {image_path}")

    ret, thresh = cv2.threshold(img, threshold_value, max_value, threshold_type)

    return thresh


if __name__ == '__main__':
    # Example usage (K-Means)
    try:
        segmented_image_kmeans = segment_image_kmeans("image.jpg", n_clusters=3) # Replace 'image.jpg' with your image path
        cv2.imwrite("segmented_kmeans.jpg", segmented_image_kmeans)
        print("K-Means segmentation complete. Saved as segmented_kmeans.jpg")

    except ValueError as e:
        print(f"Error during K-Means segmentation: {e}")
    except FileNotFoundError:
        print("Error: image.jpg not found. Please provide the correct path.")

    # Example usage (Watershed)
    try:
        segmented_image_watershed = segment_image_watershed("image.jpg") # Replace 'image.jpg' with your image path
        cv2.imwrite("segmented_watershed.jpg", segmented_image_watershed)
        print("Watershed segmentation complete. Saved as segmented_watershed.jpg")

    except ValueError as e:
        print(f"Error during Watershed segmentation: {e}")
    except FileNotFoundError:
        print("Error: image.jpg not found. Please provide the correct path.")


    # Example usage (Simple Thresholding)
    try:
        segmented_image_threshold = segment_image_simple_thresholding("image.jpg", threshold_value=127, threshold_type=cv2.THRESH_BINARY)  # Replace 'image.jpg' with your image path
        cv2.imwrite("segmented_threshold.jpg", segmented_image_threshold)
        print("Simple thresholding segmentation complete. Saved as segmented_threshold.jpg")

    except ValueError as e:
        print(f"Error during simple thresholding: {e}")
    except FileNotFoundError:
        print("Error: image.jpg not found. Please provide the correct path.")
```
👁️ Viewed: 9

Comments