打开按名称排序的图像 - PIL - Image.open()

时间:2017-06-26 15:40:23

标签: python python-2.7 python-imaging-library

我将目录告知我的代码,并且必须打开此目录中的所有图像,例如:

1-11.jpg
2-11.jpg
3-11.jpg
4-11.jpg
...
10-11.jpg
11-11.jpg
...

它打开所有文件,但我需要它按名称打开已排序的文件当前没有发生的内容...我该怎么做?

我的代码:

def convert_to_gray_scale(path, grayfilename):
    global image

    image = Image.open(path)

    # Converts the color image to grayscale
    image = image.convert("L")

    image.save(grayfilename)

directory = raw_input('\nEnter the directory of the image database: ')

# Creates the directory to store grayscale images
os.mkdir('GrayImages')

# Call the functions
for fn in glob.glob('*.jpg'):
    print '\nImage:',fn

    # Gets the file name without the extension
    f = glob.os.path.splitext(fn)[0]

    # Converts images in grayscale and saves them in GrayImages directory
    convert_to_gray_scale(fn, 'GrayImages/' + f + '_gray.jpg')

3 个答案:

答案 0 :(得分:1)

只要您要订购的所有图像都在同一目录中,您只需执行以下操作即可:

import os, sys

path_sorted = sorted(os.listdir(path))

答案 1 :(得分:0)

这可能是一个非常简单的解决方案。

import os
for i in range(1, 12):
    os.system("start {}-11.jpg".format(i))

答案 2 :(得分:0)

假设您正在使用列表,只需在打开文件之前对其进行排序: list.sort()或sorted(list)

https://wiki.python.org/moin/HowTo/Sorting

def numeric_comparison(x, y):
    return int(x.split('-')[0]) - int(y.split('-')[0])

def convert_to_gray_scale(path, grayfilename):
    global image

    image = Image.open(path)

    # Converts the color image to grayscale
    image = image.convert("L")

    image.save(grayfilename)

directory = raw_input('\nEnter the directory of the image database: ')

# Creates the directory to store grayscale images
os.mkdir('GrayImages')

# Get the jpg files then sort them
sorted_files = sorted(glob.glob('*.jpg'), cmp=numeric_comparison)

# Call the functions
for fn in sorted_files:
    print '\nImage:',fn

    # Gets the file name without the extension
    f = glob.os.path.splitext(fn)[0]

    # Converts images in grayscale and saves them in GrayImages directory
    convert_to_gray_scale(fn, 'GrayImages/' + f + '_gray.jpg')
相关问题