为什么我在尝试将图像分成两半时出现“平铺无法扩展外部图像”错误

Why am I getting tile cannot extend outside image error when trying to split image in half

我的程序应该拍摄一张图像并将其垂直分成 n 个部分,然后将这些部分保存为单独的 png 文件。 2 个部分应该看起来像这样

我现在遇到问题,我得到的是图像的前半部分已正确保存,然后在尝试裁剪后半部分时出现以下错误: SystemError: tile cannot extend outside image

我正在处理的图像有

它计算出要裁剪的矩形是:

我的问题是:为什么这个子矩形超出范围?如何修复它才能正确地将我的图像切成两半,如图所示?

from PIL import Image, ImageFilter


im = Image.open("image.png")
width, height = im.size
numberOfSplits = 2
splitDist = width / numberOfSplits #how many pixels each crop should be in width
print(width, height) #prints 1180, 842

for i in range(0, numberOfSplits):
    x = splitDist * i
    y = 0
    w = splitDist
    h = height

    print(x, y, w, h)
    #first run through prints 0.0, 0, 590.0, 842
    #second run through prints 590.0, 0, 590.0, 842 then crashes

    croppedImg = im.crop((x,y,w,h)) #crop the rectangle into my x,y,w,h
    croppedImg.save("images\new-img" + str(i) + ".png") #save to file

框的所有坐标 (x, y, w, h) 都是从图像的左上角开始测量的。

所以盒子的坐标应该是(x, y, w+x, h+y)。对代码进行以下更改。

for i in range(0, numberOfSplits):
    x = splitDist * i
    y = 0
    w = splitDist+x
    h = height+y