Back to Home

Sort images by resolution using Python and PIL

Python · PIL · sorting pictures by resolution

Sort images by resolution using Python and PIL

    image

    I wanted to register on Habré, but I don’t have any special knowledge, and the audience is just the opposite, I decided to try to lay out a python script that I wrote at the request of a friend for a bottle of 7ap :) The script helped me to organize a dump of pictures ~ 15GB.

    The script goes through the directory and creates folders in it in the form of WidthHeight and shoves the images corresponding in resolution to it.

    PS Errors are not made by one who does nothing.



    Copy Source | Copy HTML
    1. #!/usr/bin/env python
    2. # -*- coding: UTF-8 -*-
    3. """ sorts images by resolution"""
    4.  
    5. import os,sys
    6. from PIL import Image
    7.  
    8. # задаёт директорию для сортировки
    9. dirname = os.path.abspath(sys.argv[1])
    10. try:
    11.     newdir = os.path.abspath(sys.argv[2])
    12. except:
    13.     newdir = dirname
    14.  
    15. def image_sort(dirname, newdir, recur= 0):
    16.     if not recur:print 'sorting started ...' # если главная папка
    17.     else: print 'sorting started in %s...'%dirname # если подпапка
    18.  
    19. # собирает все подпапки в список и рекурсивно обходит
    20.  
    21.     imagelist = []
    22.  
    23.     if os.path.isdir(dirname):
    24.         for x in os.listdir(dirname):
    25.             absx = dirname+os.sep+x
    26.             if os.path.isfile(absx):imagelist.append(absx)
    27.             else:
    28.                 #print 'summon subsort in %s'%x
    29.                 image_sort(absx, newdir+os.sep+x,recur=1)
    30.         # проходит по содержимому папки/подпапки
    31.         for name in imagelist:
    32.             try:
    33.                 resolution = Image.open(name).size #получить разрешение
    34.             except IOError:
    35.                 print 'seems not image: '+ name, '/n'
    36.                 continue
    37.             imdir = '%sx%s'%(resolution[ 0],resolution[1])
    38.             imdir = os.path.join(newdir,imdir)
    39.             #если имя папки такое же как и разрешение картинки
    40.             if os.path.split(dirname)[-1] == os.path.split(imdir)[-1]:
    41.                 continue
    42.             elif not os.path.exists(imdir):
    43.                 #print 'making dir %s'%imdir
    44.                 os.mkdir(imdir)
    45.             try:
    46.                 os.system('move "%s" "%s"'%(name,imdir))
    47.             except WindowsError:
    48.                 print 'error with '+ name, '/n'
    49.     if not recur:print 'sorting completed!'
    50.  
    51. if __name__ == '__main__':
    52.     image_sort(dirname, newdir)

    Read Next