我创建一个脚本来裁剪图像,并将它们保存在多个相等的部分中。我试着用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:\Users\jra02028\Anaconda3\lib\site-packages\PIL\Image.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'发布于 2022-09-21 03:24:16
由于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:\2022\Python program\Bloc1\Prediction bloc1\Test images\zchop.predicted_imageCAO2.x000.y000.jpghttps://stackoverflow.com/questions/73794743
复制相似问题