PIL仅保存第一张图像

时间:2013-05-07 01:29:34

标签: python python-imaging-library

我正在尝试进行一些批量图像处理,但是在创建图像后我无法保存。以下是所有代码:

import Image
import os
import random

training_images = []
training_path = 'cropped'
background_images = []
background_path = 'background'
training_file = 'train'

def get_image_list(file_path):
    return os.listdir(file_path)

def rotate_randomely(im):
    number = random.randint(1, 6)
    if number == 1:
        return im.transpose(Image.FLIP_LEFT_RIGHT)
    elif number == 2:
        return im.transpose(Image.FLIP_TOP_BOTTOM)
    elif number == 3:
        return im.transpose(Image.ROTATE_90)
    elif number == 4:
        return im.transpose(Image.ROTATE_180)
    elif number == 5:
        return im.transpose(Image.ROTATE_270)
    else:
        return im

def get_random_point(maxX, maxY):
    x = random.randint(0, maxX)
    y = random.randint(0, maxY)
    return x, y 

def insert_image(from_image, onto_image):

    from_image = resize_smaller(from_image, onto_image.size)
    x, y = get_random_point(onto_image.size[0] - from_image.size[0], onto_image.size[1] - from_image.size[0])
    onto_image.paste(from_image, (x, y))
    width = from_image.size[0]
    height = from_image.size[1]
    return x, y, width, height

def resize_smaller(image, maxXY):
    if image.size[0] > maxXY[0] or image.size[1] > maxXY[1]:
        image = image.resize((image.size[0] / 2, image.size[1] / 2))
    if image.size[0] > maxXY[0] or image.size[1] > maxXY[1]:
        resize_smaller(image, maxXY)
    else:
        return image

training_images = get_image_list(training_path)
background_images =  get_image_list(background_path)
print('training_images size', len(training_images))
print('background_images size', len(background_images))

for training_image in training_images:
    index = 0
    for background_image in background_images:
        name = background_image
        training_image = Image.open(training_path + '/' + training_image)
        background_image = Image.open(background_path + '/' + background_image)
        training_image = rotate_randomely(training_image)
        x, y, width, height = insert_image(training_image, background_image)
        background_image.save('images/' + str(index) + name)
        index = index + 1

输出:     ('training_images size', 7)     ('background_images size', 1)。所以它正确地找到了图像,但是当我查看结果时,只保存了一个图像,并且它只有一个预先设置为图像名称的图像。但我知道它经历了每个图像,所以应该有七个。

我一直在看这个,我只是看不出哪里出错了。关于我不知道的pil's save方法有什么奇怪的吗?

1 个答案:

答案 0 :(得分:1)

index = 0置于上部for循环之外,否则它将在每次迭代时变为0并保存在旧文件的顶部。