from os import listdir
from PIL import Image, ExifTags, ImageStat

files = listdir("colors")

# Just to be safe:
if ".DS_Store" in files:
    files.remove(".DS_Store")

# This list will contain TUPLES of the form (AVG_HUE,IMAGE)
# Where AVG_HUE is the average hue of the image stored in IMAGE
sorted_images = []

# Loop over all files in the directory:
for f in files:
    img = Image.open( "colors/" + f )

    # Convert the image to HSV and use the
    # PIL ImageStat tool to find the average hue of the image
    img_hsv = img.convert(mode="HSV")
    average_hue = ImageStat.Stat(img_hsv).mean[0]
    # If the average hue is less than 10, it's probably a grayscale image,
    # so let's skip it. Don't add it to sorted_images
    if average_hue < 10:
        continue

    # Loop over the sorted_images list and determine where
    # to insert the current image based on its average_hue value
    i = 0
    while i < len(sorted_images) and average_hue > sorted_images[i][0]:
        i = i + 1
    sorted_images.insert(i, (average_hue,img) )

# Now create a new blank image that is
# 200 pixels tall and as wide as the length of the sorted_images list times 200
output_image = Image.new("RGB", (200*len(sorted_images),200), (255,255,255) )
x = 0
# Loop over sorted_images, which will iterate over each image in
# the order determined above
for img in sorted_images:
    # Resize each into a 200x200 box
    img[1].thumbnail((200,200))
    # And paste it into the new blank image at x,0
    output_image.paste(img[1],(x,0))
    # Increase x by 200 for the location of the next image
    x = x + 200

# Save and display the new image
output_image.save("new.jpg")
output_image.show()
