2013-05-07 70 views
1

我正在嘗試執行一些批處理圖像處理,但在創建後一次保存圖像時遇到問題。這裏是所有的代碼:PIL僅保存第一個圖像

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)。所以它正確地找到了圖像,但是當我查看結果時,只有一個圖像被保存,並且只有圖像名稱的前0。但我知道它通過每張圖片,所以應該有七張。

我一直在看這一段時間,我只是不明白我出錯的地方。我不知道pil的保存方法有什麼奇怪的地方嗎?

回答

1

index = 0置於循環的上方之外,否則每次迭代它將變爲0並保存在舊文件的頂部。

+1

它總是小事... – TomJ 2013-05-07 02:04:54