Slow image processing with Python and PIL
Question: I'm trying to sort the pixels of images in order of RGB values. Being new to
Python i tried this:

    
    
    from PIL import Image
    
    source = Image.open("source.jpg")
    colors = source.getcolors(source.size[0] * source.size[1]) #maxcolor value =256, get   all colors with source.size[0] * source.size[1]
    pixels = []
    for i, color in colors:
        pixels.extend(i * [color])
        pixels.sort()
        new = Image.new('RGB', source.size)
        new.putdata(pixels) 
        new.save("new.png")
    

It works quiet well for small files around 40x40 pixels. But the goal was to
use it on photos with up to 3000x2000 resolution, i tried running it but after
two hours there was still no end in sight. Can the code be optimized, did i do
something completly wrong or is Python simply not suited for that kind of
task?


Answer: Indentation in Python is key, otherwise you can run code you wouldn't for each
iteration.

Here you are saving your file each time you loop as your image generation is
indented. Instead, try:

    
    
    from PIL import Image
    
    source = Image.open("source.jpg")
    colors = source.getcolors(source.size[0] * source.size[1]) #maxcolor value =256, get   all colors with source.size[0] * source.size[1]
    pixels = []
    for i, color in colors:
        pixels.extend(i * [color])
    pixels.sort()
    new = Image.new('RGB', source.size)
    new.putdata(pixels) 
    new.save("new.png")
    

