import os
import shutil
import numpy as np
import tkinter as tk
from tkinter import filedialog, messagebox
from sklearn.cluster import DBSCAN
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from keras.applications.resnet50 import ResNet50, preprocess_input
from keras.preprocessing import image
from keras.models import Model
from tqdm import tqdm # For progress bar
import threading # To run the clustering in a separate thread
def choose_folder():
"""Open a folder selection dialog and return the path."""
return filedialog.askdirectory()
def extract_resnet50_features(img_path, model):
"""Extract ResNet50 features from an image."""
try:
img = image.load_img(img_path, target_size=(224, 224))
except Exception as e:
print(f"Error loading image {img_path}: {e}")
return None
img_data = image.img_to_array(img)
img_data = np.expand_dims(img_data, axis=0)
img_data = preprocess_input(img_data)
features = model.predict(img_data)
return features.flatten()
def sort_images_by_likeness():
"""Cluster images without specifying the number of clusters using DBSCAN."""
source_folder = source_var.get()
if not source_folder:
messagebox.showwarning("Incomplete Information", "Please select the source folder path.")
return
# Run the clustering in a separate thread to keep the GUI responsive
threading.Thread(target=process_clustering, args=(source_folder,)).start()
def process_clustering(source_folder):
try:
# Update status
update_status("Loading model...")
# Load pre-trained ResNet50 model + higher level layers (Excluding final fully connected layers)
base_model = ResNet50(weights='imagenet', include_top=False, pooling='avg')
model = Model(inputs=base_model.input, outputs=base_model.output)
# List image files
image_files = [f for f in os.listdir(source_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))]
if not image_files:
messagebox.showwarning("No Images Found", "The selected folder does not contain any supported image files.")
update_status("")
return
feature_vectors = []
valid_image_files = []
# Extract features with progress bar
update_status("Extracting features...")
for image_file in tqdm(image_files, desc="Processing Images"):
image_path = os.path.join(source_folder, image_file)
features = extract_resnet50_features(image_path, model)
if features is not None:
feature_vectors.append(features)
valid_image_files.append(image_file)
else:
print(f"Skipping {image_file} due to loading error.")
if not feature_vectors:
messagebox.showerror("Feature Extraction Failed", "No features could be extracted from the images.")
update_status("")
return
# Standardize features before PCA
update_status("Standardizing features...")
scaler = StandardScaler()
feature_vectors = scaler.fit_transform(feature_vectors)
# Dimensionality Reduction
update_status("Reducing dimensions with PCA...")
pca = PCA(n_components=0.95, random_state=42) # Retain 95% variance
feature_vectors = pca.fit_transform(feature_vectors)
# Optionally, further reduce dimensions with UMAP (if installed)
# from umap import UMAP
# update_status("Further reducing dimensions with UMAP...")
# umap = UMAP(n_components=50, random_state=42)
# feature_vectors = umap.fit_transform(feature_vectors)
# Perform DBSCAN clustering with adjusted parameters
update_status("Clustering with DBSCAN...")
dbscan = DBSCAN(eps=0.5, min_samples=3, metric='euclidean', n_jobs=-1)
labels = dbscan.fit_predict(feature_vectors)
unique_labels = set(labels)
if -1 in unique_labels:
unique_labels.remove(-1) # Handle noise separately
# Create cluster folders
update_status("Creating cluster folders...")
for label in unique_labels:
cluster_folder = os.path.join(source_folder, f"cluster_{label}")
os.makedirs(cluster_folder, exist_ok=True)
# Handle noise
noise_folder = os.path.join(source_folder, "cluster_noise")
if -1 in set(labels):
os.makedirs(noise_folder, exist_ok=True)
# Move images to respective folders with progress bar
update_status("Moving images to cluster folders...")
for index, image_file in tqdm(enumerate(valid_image_files), total=len(valid_image_files), desc="Moving Images"):
cluster_index = labels[index]
source_path = os.path.join(source_folder, image_file)
if cluster_index == -1:
dest_path = os.path.join(noise_folder, image_file)
else:
dest_path = os.path.join(source_folder, f"cluster_{cluster_index}", image_file)
shutil.move(source_path, dest_path)
messagebox.showinfo("Success", "Images have been sorted into similarity groups successfully!")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
finally:
update_status("")
def update_status(message):
status_var.set(message)
root.update_idletasks()
# Initialize GUI
root = tk.Tk()
root.title("Image Sorter by Likeness")
root.geometry("400x200")
source_var = tk.StringVar()
status_var = tk.StringVar()
# Create GUI elements
frame = tk.Frame(root)
frame.pack(pady=10, padx=10, fill='x')
tk.Label(frame, text="Select Source Folder:").pack(anchor='w')
browse_frame = tk.Frame(frame)
browse_frame.pack(fill='x', pady=5)
tk.Entry(browse_frame, textvariable=source_var, state='readonly').pack(side='left', fill='x', expand=True, padx=(0,5))
tk.Button(browse_frame, text="Browse", command=lambda: source_var.set(choose_folder())).pack(side='right')
tk.Button(frame, text="Sort Images by Likeness", command=sort_images_by_likeness).pack(pady=10, fill='x')
# Status Label
status_label = tk.Label(root, textvariable=status_var, relief='sunken', anchor='w')
status_label.pack(side='bottom', fill='x')
# Execute the Tkinter main loop
root.mainloop()