|
import cv2 |
|
import numpy as np |
|
from sklearn.cluster import KMeans |
|
|
|
def segment_image(image_path, k=2, resize_shape=(256, 256)): |
|
|
|
img = cv2.imread(image_path) |
|
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) |
|
img = cv2.resize(img, resize_shape) |
|
|
|
|
|
img_normalized = img / 255.0 |
|
|
|
|
|
img_denoised = cv2.GaussianBlur(img_normalized, (5, 5), 0) |
|
|
|
|
|
img_flat = img_denoised.reshape(-1, 3) |
|
|
|
|
|
kmeans = KMeans(n_clusters=k, random_state=0).fit(img_flat) |
|
labels = kmeans.labels_ |
|
|
|
|
|
segmented_img = labels.reshape(resize_shape) |
|
|
|
|
|
segmented_img_gray = (segmented_img * 255).astype(np.uint8) |
|
|
|
return img, segmented_img_gray |