Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 881
Keatinge Avatar asked Apr 08 '16 05:04

Keatinge


1 Answers

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
like image 55
supreeth manyam Avatar answered Sep 19 '22 13:09

supreeth manyam