简体   繁体   中英

How to save PIL images in a loop

I'm trying to use a function that itterates over a data frame of image locations and transforms those images then saves them back in the same directory.

Head of the datafram that holds the images

保存图像的datafram的头部

The function I defined is as follows:

from PIL import Image, ImageEnhance

def image_build(img, df):
    for img in df[img]:
        count = 1
        pic = df[img]
        if df['label'].any() == 0:
            im = Image.open(df[img])
            enh = ImageEnhance.Contrast(im)
            im = enh.enhance(1.9)
            im = im.rotate(90)
            im = im.transpose(Image.FLIP_LEFT_RIGHT)
            im = im.resize(224, 224)
            save_dir = 'N:/Users/Howell/Kaggle/X_Ray/chest_xray/train/NORMAL/'
            im.save(save_dir/'new_image_'+count+'.jpeg')
            count += count + 1
            print(count)

Then I try to use this function:

image_build('image', train_data)

But I'm getting the following error:

> --------------------------------------------------------------------------- KeyError                                  Traceback (most recent call
> last)
> C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\indexes\base.py
> in get_loc(self, key, method, tolerance)    2656             try:
> -> 2657                 return self._engine.get_loc(key)    2658             except KeyError:
> 
> pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
> 
> pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
> 
> pandas/_libs/hashtable_class_helper.pxi in
> pandas._libs.hashtable.PyObjectHashTable.get_item()
> 
> pandas/_libs/hashtable_class_helper.pxi in
> pandas._libs.hashtable.PyObjectHashTable.get_item()
> 
> KeyError:
> WindowsPath('N:/Users/Howell/Kaggle/X_Ray/chest_xray/train/NORMAL/IM-0580-0001.jpeg')
> 
> During handling of the above exception, another exception occurred:
> 
> KeyError                                  Traceback (most recent call
> last) <ipython-input-144-d17ac9ecd789> in <module>
> ----> 1 image_build('image', train_data)
> 
> <ipython-input-143-cf988e867715> in image_build(img, df)
>       2     for img in df[img]:
>       3         count = 1
> ----> 4         pic = df[img]
>       5         if df['label'].any() == 0:
>       6             im = Image.open(df[img])
> 
> C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\frame.py
> in __getitem__(self, key)    2925             if self.columns.nlevels
> > 1:    2926                 return self._getitem_multilevel(key)
> -> 2927             indexer = self.columns.get_loc(key)    2928             if is_integer(indexer):    2929                 indexer = [indexer]
> 
> C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\indexes\base.py
> in get_loc(self, key, method, tolerance)    2657                
> return self._engine.get_loc(key)    2658             except KeyError:
> -> 2659                 return self._engine.get_loc(self._maybe_cast_indexer(key))    2660        
> indexer = self.get_indexer([key], method=method, tolerance=tolerance) 
> 2661         if indexer.ndim > 1 or indexer.size > 1:
> 
> pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
> 
> pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
> 
> pandas/_libs/hashtable_class_helper.pxi in
> pandas._libs.hashtable.PyObjectHashTable.get_item()
> 
> pandas/_libs/hashtable_class_helper.pxi in
> pandas._libs.hashtable.PyObjectHashTable.get_item()
> 
> KeyError:
> WindowsPath('N:/Users/Howell/Kaggle/X_Ray/chest_xray/train/NORMAL/IM-0580-0001.jpeg')

I've just discovered Pillow so I'm not sure what I'm doing wrong.

Now I'm changed the function to the following and it runs without error but does nothing...not even the print statement.

def image_build(img, df):
    for img in df[img]:
        count = 1

        if df['label'].any() == 0:
            print('pass_image')
            pic = df[img]
            im = Image.open(pic)
            enh = ImageEnhance.Contrast(im)
            img = enh.enhance(1.9)
            img = im.rotate(90)
            img = im.transpose(Image.FLIP_LEFT_RIGHT)
            img = im.resize(224, 224)
            save_dir = 'N:/Users/Howell/Kaggle/X_Ray/chest_xray/train/NORMAL/'
            img.save(save_dir / 'new_image_'+count+'.jpeg')
            count += 1

With help from multiple people, the following runs but only produces one picture and gets stuck printing on count 3 .

from PIL import Image, ImageEnhance

def image_build(img, df):
    for index,row in df.iterrows():
        count = 1
        pic = row[img]
        if row['label'] == 0:
            im = Image.open(pic)
            enh = ImageEnhance.Contrast(im)
            im = enh.enhance(1.9)
            im = im.rotate(90)
            im = im.transpose(Image.FLIP_LEFT_RIGHT)
            im = im.resize((750, 500))
            save_dir = Path('N:/Users/Howell/Kaggle/X_Ray/chest_xray/train/NORMAL/')
            count2 = str(count)
            im.save(save_dir / str('new_image_'+count2+'.jpeg'))
            count += count + 1
            print(count)
        else:
            pass

You use the same variable img again

from PIL import Image, ImageEnhance

def image_build(img, df):
    for index,row in df.iterrows():
        count = 1
        pic = row[img]
        if row['label'] == 0:
            im = Image.open(pic)
            enh = ImageEnhance.Contrast(im)
            im = enh.enhance(1.9)
            im = im.rotate(90)
            im = im.transpose(Image.FLIP_LEFT_RIGHT)
            im = im.resize(224, 224)
            save_dir = 'N:/Users/Howell/Kaggle/X_Ray/chest_xray/train/NORMAL'
            im.save(f'{save_dir}/new_image_{count}.jpeg'))
            count += count + 1
            print(count)

Try this if it works:

def image_build(img, df):
    count = 1  #  define count here so that it do not get intialised for each iteration
    for img in df[img]:
        pic = df[img]
        if df['label'].any() == 0:
            im = Image.open('your_image_path')
            enh = ImageEnhance.Contrast(im)
            img = enh.enhance(1.9)
            img = im.rotate(90)
            img = im.transpose(Image.FLIP_LEFT_RIGHT)
            img = im.resize((224, 224))
            save_dir = 'your path'
            img.save(save_dir + 'new_image_'+'1'+'.jpeg')
            count += 1 

Ok. I finally got it! Move the count before the iterrows()

Edited

from PIL import Image, ImageEnhance

def image_build(img, df):
    count = 1
    for index,row in df.iterrows():
        pic = row[img]
        if row['label'] == 0:
            im = Image.open(pic)
            enh = ImageEnhance.Contrast(im)
            im = enh.enhance(1.9)
            im = im.rotate(90)
            im = im.transpose(Image.FLIP_LEFT_RIGHT)
            im = im.resize((750, 500))
            save_dir = Path('N:/Users/Howell/Kaggle/X_Ray/chest_xray/train/NORMAL/')
            count2 = str(count)
            im.save(save_dir + str('new_image_'+count2+'.jpeg'))
            count += count + 1
            print(count)
        else:
            pass

I think this is the problem with the path of the file. replace / with \\(double backslash) or \\

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM