简体   繁体   English

Python PIL裁剪文件夹中的所有图像

[英]Python PIL Crop all Images in a Folder

Currently I am trying to crop all images inside a folder under the address of: C:\\\\Users\\\\xie\\\\Desktop\\\\tiff\\\\Bmp and then resave them into the same folder. 目前,我正在尝试裁剪以下文件夹中的所有图像: C:\\\\Users\\\\xie\\\\Desktop\\\\tiff\\\\Bmp ,然后将它们重新保存到同一文件夹中。 Below is the code I am trying to experiment with, both run without error but does nothing. 下面是我要尝试的代码,它们都可以正常运行,但是什么也不做。 Also note I am using windows as platform. 另请注意,我使用Windows作为平台。

Code 1: 代码1:

from PIL import Image
import os.path, sys

path = "C:\\Users\\xie\\Desktop\\tiff\\Bmp"
dirs = os.listdir(path)

def crop():
    for item in dirs:
        if os.path.isfile(path+item):
            im = Image.open(path+item)
            f, e = os.path.splitext(path+item)
            imCrop = im.crop(30, 10, 1024, 1004)
            imCrop.save(f + 'Cropped.bmp', "BMP", quality=100)

crop()

Code 2: 代码2:

for f in os.listdir("C:\\Users\\xie\\Desktop\\tiff\\Bmp"):
    for f in ("C:\\Users\\xie\\Desktop\\tiff\\Bmp"):
        if f.endswith('.bmp'):
            print (f, end=" ")
            i = Image.open(f)
            area = (30, 10, 1024, 1004)
            cropped_i = i.crop(area)
            cropped_i.show()
            cropped_i.save('Cropped{}.bmp', "BMP", quality=100, optimize=True)

Thanks, any help or suggestions are greatly appreciated! 谢谢,任何帮助或建议,我们将不胜感激!

This is more or less a rough version of code, I used with opencv, it should work the same for PIL also 这或多或少是代码的粗糙版本,我与opencv一起使用,它对于PIL也应相同

import glob
import numpy as np
from PIL import Image
image_list = []
for filename in glob.glob('name_of_folder/*.jpg'): 
    im=Image.open(filename)
    image_list.append(im)
a=0
c=[]
for i in range(0,len(image_list)):
    #ur image cropping and other operations in here for each image_list[i]
    c.append(image_list[i])
    c[i].save()

Code 1 : Corrected 代码1:已更正

This is your corrected code, you almost had it right, you have to join the path correctly, in your code you weren't adding a separator / between the path and the filename. 这是您的更正代码,几乎正确,必须正确连接路径,在代码中未在路径和文件名之间添加分隔符/ by using os.path.join you can combine a directory path and a filename . 通过使用os.path.join ,可以组合directory pathfilename

Furthermore, crop takes a tuple of 4, not 4 arguments. 此外,crop的元组为4,而不是4。

from PIL import Image
import os.path, sys

path = "C:\\Users\\xie\\Desktop\\tiff\\Bmp"
dirs = os.listdir(path)

def crop():
    for item in dirs:
        fullpath = os.path.join(path,item)         #corrected
        if os.path.isfile(fullpath):
            im = Image.open(fullpath)
            f, e = os.path.splitext(fullpath)
            imCrop = im.crop((30, 10, 1024, 1004)) #corrected
            imCrop.save(f + 'Cropped.bmp', "BMP", quality=100)

crop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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