尝试将图像分成两半时,为什么我得到图块无法扩展图像外错误

时间:2016-04-08 05:34:53

标签: python image python-imaging-library crop

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

enter image description here

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

我正在使用的图片

  • 宽度:1180像素
  • 身高:842px

它计算裁剪的矩形是:

  • (0.0, 0, 590.0, 842) - 这可以正常使用
  • (590.0, 0, 590.0, 842) - 这会导致程序崩溃

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

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

1 个答案:

答案 0 :(得分:13)

框(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