Image Segmentation with K-Means Clustering in Python
#pip install scikit-learn matplotlib opencv-python
import matplotlib as mpl
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
image = mpl.image.imread("korunga.jpg")
plt.imshow(image)
print(image.shape)
#(1599, 719, 3)
X=image.reshape(-1, 3)
print(X.shape)
kmeans=KMeans(n_clusters=2, n_init=10)
kmeans.fit(X)
segmented_img=kmeans.cluster_centers_[kmeans.labels_]
segmented_img=segmented_img.reshape(image.shape)
plt.imshow(segmented_img / 255)
#resmi segmente etti
import cv2
cv2.imwrite("image1.png", cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
cv2.imwrite("image2.png", cv2.cvtColor(segmented_img.astype("uint8"), cv2.COLOR_BGR2RGB))
#image2 segmented olan
Kaynaklar
- https://www.youtube.com/watch?v=X-Y91ddBqaQ