打开进程并将特定图像保存在相关文件夹中

Open process and save specific images in related folder

我正在寻找一种方法来打开和裁剪多个 tiff 图像,然后将创建的新裁剪图像保存在同一文件夹(与我的脚本文件夹相关)中。

我当前的代码如下所示:

from PIL import Image
import os,platform

filespath = os.path.join(os.environ['USERPROFILE'],"Desktop\Python\originalImagesfolder")

for file in os.listdir(filespath):
    if file.endswith(".tif"):
        im = Image.open(file)
        im.crop((3000, 6600, 3700, 6750)).save(file+"_crop.tif")

此脚本返回错误:

Traceback (most recent call last):

File "C:\Users...\Desktop\Python\script.py", line 22, in im = Image.open(file)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 2219, in open fp = builtins.open(fp, "rb") FileNotFoundError: [Errno 2] No such file or directory: 'Image1Name.tif'

'Image1Name.tif' 是我在文件夹中尝试处理的第一张 tif 图像。我不明白脚本如何在找不到文件的情况下给出文件名。有帮助吗?

PS:我在 python 和代码方面有 2 天的经验,一般来说。抱歉,如果答案显而易见

[EDIT/Update] 由于 vttran 和 ChrisGuest 的回答,修改了我的初始代码后,变成了这个:

from PIL import Image
import os,platform

filespath = os.path.join(os.environ['USERPROFILE'],"Desktop\Python\originalImagesfolder")

for file in os.listdir(filespath):
    if file.endswith(".tif"):
        filepath = os.path.join(filespath, file)
        im = Image.open(filepath)
        im.crop((3000, 6600, 3700, 6750)).save("crop"+file)

脚本返回一条新的错误消息:

Traceback (most recent call last):
File "C:/Users/.../Desktop/Python/script.py", line 11, in im.crop((3000, 6600, 3700, 6750)).save("crop"+file)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 986, in crop self.load()
File "C:\Python34\lib\site-packages\PIL\ImageFile.py", line 166, in load self.load_prepare()
File "C:\Python34\lib\site-packages\PIL\ImageFile.py", line 250, in load_prepare self.im = Image.core.new(self.mode, self.size) ValueError: unrecognized mode

可能有用的信息,它是 GeoTiff 格式的 Landsat8 图像。因此,TIFF 文件包含地理定位、投影...信息。如果我首先使用 Photoshop(16int tiff 格式)等软件打开并重新保存它们,该脚本就可以正常工作。

当您搜索文件名时,您使用文件路径来指定目录。

但是当您打开文件时,您只使用基本文件名。

所以你可以替换

im = Image.open(file)

filepath = os.path.join(filespath, file)
im = Image.open(filepath)

还可以考虑使用 glob 模块,您可以这样做 glob.glob(r'path\*.tif)。 避免使用 file 等内置函数作为变量名也是一种很好的做法。