Untitled
unknown
plain_text
2 years ago
1.5 kB
8
Indexable
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
image_directory = r"Image_dataset"
images = []
for filename in os.listdir(image_directory):
if filename.endswith(".jpg") or filename.endswith(".png"):
img = cv2.imread(os.path.join(image_directory, filename))
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Convert to RGB format
img = cv2.resize(img, (200, 200)) # Resize to a common size
images.append(img)
images = np.array(images)
# Flatten the images
n_samples, height, width, n_colors = images.shape
images = images.reshape((n_samples, -1))
# Number of clusters
clusters = 5
# Perform K-means clustering
kmeans = KMeans(clusters,random_state=0)
kmeans.fit(images)
# Get the labels and cluster centroids
labels = kmeans.labels_
cluster_centers = kmeans.cluster_centers_
# Reshape cluster centers into images
cluster_centers_images = cluster_centers.reshape((clusters, height, width, n_colors))
# Plot the cluster centers
plt.figure(figsize=(10, 4))
plt.subplots_adjust(top=1, bottom=0, hspace=0.05, wspace=0.05)
for i in range(clusters):
plt.subplot(1, clusters, i + 1)
plt.imshow(cluster_centers_images[i].astype(np.uint8))
plt.title(f'Cluster {i}')
plt.axis('off')
plt.show()
warnings.resetwarnings()Editor is loading...