python - 如何循环保存PIL图像

标签 python python-imaging-library

我正在尝试使用一个函数来遍历图像位置的数据框并转换这些图像,然后将它们保存回同一目录。

保存图像的数据帧的头部

Head of the datafram that holds the images

我定义的函数如下:

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)

然后我尝试使用这个函数:

image_build('image', train_data)

但我收到以下错误:

> --------------------------------------------------------------------------- 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')

我刚刚发现 Pillow,所以我不确定自己做错了什么。

现在我将函数更改为以下内容,它运行时没有错误,但什么也没做...甚至 print 语句也没有。

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

在多人的帮助下,运行了以下程序,但只生成了一张图片,并在计数 3 时卡住了。

从 PIL 导入图像,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

最佳答案

你再次使用相同的变量 img

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)

关于python - 如何循环保存PIL图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56237241/

相关文章:

python - 有条件地选择数据框行的一部分

python - 避免在循环后重复代码?

jinja2 - 如何动态显示PIL图像

python - 在Python中将图像拼接在一起

python - Linux服务器列出可以登录的用户

python - 使用 BeautifulSoup 根据内容值提取标签内容

Python:从 txt 文件的目录中计算单词并将单词计数写入单独的 txt 文件

python - 如何在屏幕上显示 PIL 图像?

python - 如何拍摄图像并获得从中心裁剪的 3x2 比例图像?

具有 Alpha channel 背景的 Python 文本