import os
import shutil
import cv2
import numpy as np
import tkinter as tk
from tkinter import filedialog, messagebox

def get_images(input_path):
    """Return all image files from the input path."""
    supported_formats = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff')
    return [f for f in os.listdir(input_path) if f.lower().endswith(supported_formats)]

def find_dominant_color(image_path, k=1):
    """Find the dominant color of an image."""
    img = cv2.imread(image_path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # Convert to RGB

    # Reshape the image to a 2D array of pixels and apply k-means
    pixels = img.reshape((-1, 3))
    pixels = np.float32(pixels)
    _, labels, palette = cv2.kmeans(pixels, k, None, 
                                    (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0), 
                                    10, cv2.KMEANS_RANDOM_CENTERS)
    
    dominant_color = palette[np.argmax(np.unique(labels, return_counts=True)[1])]
    return tuple(dominant_color.astype(int))

def sort_images_by_dominant_color(input_path):
    images = get_images(input_path)
    if not images:
        messagebox.showinfo("No Images", "No images found in the selected directory.")
        return

    output_base_path = os.path.join(input_path, "Sorted_By_Color")

    if not os.path.exists(output_base_path):
        os.makedirs(output_base_path)

    for image_file in images:
        image_path = os.path.join(input_path, image_file)

        # Determine the dominant color
        color = find_dominant_color(image_path)
        color_folder_name = f"Color_{color[0]:02X}_{color[1]:02X}_{color[2]:02X}"
        color_folder_path = os.path.join(output_base_path, color_folder_name)
        
        if not os.path.exists(color_folder_path):
            os.makedirs(color_folder_path)
        
        shutil.move(image_path, os.path.join(color_folder_path, image_file))

    messagebox.showinfo("Sorting Complete", "Images have been sorted by dominant color!")

def browse_folder():
    folder_path = filedialog.askdirectory()
    if folder_path:
        sort_images_by_dominant_color(folder_path)

def create_gui():
    app = tk.Tk()
    app.title("Image Sorter by Dominant Color")

    tk.Label(app, text="Select an Image Directory").pack(pady=10)
    tk.Button(app, text="Browse and Sort", command=browse_folder).pack(pady=20)

    app.mainloop()

if __name__ == "__main__":
    create_gui()

For this script, I am getting the following error.
[ WARN:0@6.910] global loadsave.cpp:241 cv::findDecoder imread_('C:/Users/ewkya/Desktop/Temp/COSPLAY/[Twitter] 鍗冮槼(銇°倛) 鏁ｅ浘/New folder\0003锛歵okio0131_1849404067271131333_20241024_01.jpg'): can't open/read file: check file path/integrity
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\ewkya\AppData\Local\Programs\Python\Python312\Lib\tkinter\__init__.py", line 1968, in __call__
    return self.func(*args)
           ^^^^^^^^^^^^^^^^
  File "D:\Projects\Programming Language\Python\Notepad++\Image Sorting\ImgSort.py", line 57, in browse_folder
    sort_images_by_dominant_color(folder_path)
  File "D:\Projects\Programming Language\Python\Notepad++\Image Sorting\ImgSort.py", line 43, in sort_images_by_dominant_color
    color = find_dominant_color(image_path)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Projects\Programming Language\Python\Notepad++\Image Sorting\ImgSort.py", line 16, in find_dominant_color
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # Convert to RGB
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
cv2.error: OpenCV(4.10.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:196: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'