tkinter裁剪多个图像OSError:[Erno 22]



我创建了一个脚本来裁剪图像并将其保存为多个相等的部分。我试着用tkinter来称呼它,但我总是犯这个错误。似乎错误告诉我路径的名称太大了,但我该如何解决这个问题。

有什么建议吗?

def crop():
global file, basename, chopsize, infile, path
infile = filedialog.askopenfilename(initialdir="C:\2022\Python program\Bloc1\Input bloc1",
title= "Select a File", filetypes=(("jpg files", ".jpg"),("all files","*.*")))

chopsize = 400
path = Path(infile)
print(path.name)
#basename = os.path.basename(infile)

img0 = Image.open(infile)
#img0 = ImageTk.PhotoImage(img0)
#img0 = Image.open(infile)
#img0 = Tk.PhotoImage(Image.open(infile))
#img0 = Image.open(infile, "r")
#img0 = PIL.Image.open(infile)
#img0 = cv2.imread(basename)
#img = ImageOps.grayscale(img)
width, height = img0.size

print(img0.size)

# Save Chops of original image
for x0 in range(0, width, chopsize):
for y0 in range(0, height, chopsize):
box = (x0, y0,
x0+chopsize if x0+chopsize <  width else  width - 1,
y0+chopsize if y0+chopsize < height else height - 1)
print('%s %s' % (infile, box))
#img.crop(box).save('zchop.%s.x%03d.y%03d.jpg' % (infile.replace('.jpg',''), x0, y0))

img0.crop(box).save("C:/2022/Python program/Bloc1/Prediction bloc1/Test images/zchop.%s.x%03d.y%03d.jpg" % (infile.replace('.jpg',''), x0, y0))
#img.crop(box).save("C:/2022/Python program/Bloc1/Prediction bloc1/Test images/zchop.%s.x%03d.y%03d.jpg" % (infile.replace('.jpg',''), x0, y0))

File "C:Usersjra02028Anaconda3libsite-packagesPILImage.py", line 2317, in save
fp = builtins.open(filename, "w+b")
OSError: [Errno 22] Invalid argument: 'C:/2022/Python program/Bloc1/Prediction bloc1/Test images/zchop.C:/2022/Python program/Bloc1/Input bloc1/predicted_imageCAO2.x000.y000.jpg'

由于infile已经是一个完整路径名,下面的代码将把这个完整路径名放在另一个完整的路径名中:

"C:/2022/Python program/Bloc1/Prediction bloc1/Test images/zchop.%s.x%03d.y%03d.jpg" % (infile.replace('.jpg',''), x0, y0)

其产生无效的完整路径名。

要构建所需的完整路径名,更容易使用pathlib模块:

from pathlib import Path
...
# convert infile to Path object
infile = Path(infile)
# output folder
outdir = Path("C:/2022/Python program/Bloc1/Prediction bloc1/Test images")
# construct the output filename
outname = "zchop.%s.x%03d.y%03d%s" % (infile.stem, x0, y0, infile.suffix)
# suggest to use f-string
#outname = f"zchop.{infile.stem}.x{x0:03}.y{y0:03}{infile.suffix}"
# construct the output full pathname
outfile = outdir / outname

那么outfile就像

C:2022Python programBloc1Prediction bloc1Test imageszchop.predicted_imageCAO2.x000.y000.jpg

最新更新