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

Keatinge picture Keatinge · Apr 8, 2016 · Viewed 29.7k times · Source

My program is supposed to take an image and split it vertically into n sections, then save the sections as individual png files. It should look something like this for 2 sections

enter image description here

I'm having problems right now, what I'm getting is the first half of my image get saved properly, and then I'm getting the following error when it tries to crop the second half: SystemError: tile cannot extend outside image

The image I'm working with has

  • Width: 1180px
  • Height: 842px

The rectangles it calculates to crop is:

  • (0.0, 0, 590.0, 842) - this works properly
  • (590.0, 0, 590.0, 842) - this crashes the program

My questions is: Why is this sub rectangle out of bounds and how can I fix it to properly slice my image in half like shown in picture?

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

Answer

supreeth manyam picture supreeth manyam · Apr 8, 2016

All the coordinates of box (x, y, w, h) are measured from the top left corner of the image.

so the coordinates of the box should be (x, y, w+x, h+y). Make the following changes to the code.

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