pythonimagesplitpython-imaging-librarycrop

How to Split Image Into Multiple Pieces in Python


I'm trying to split a photo into multiple pieces using PIL.

def crop(Path,input,height,width,i,k,x,y,page):
    im = Image.open(input)
    imgwidth = im.size[0]
    imgheight = im.size[1]
    for i in range(0,imgheight-height/2,height-2):
        print i
        for j in range(0,imgwidth-width/2,width-2):
            print j
            box = (j, i, j+width, i+height)
            a = im.crop(box)
            a.save(os.path.join(Path,"PNG","%s" % page,"IMG-%s.png" % k))
            k +=1

but it doesn't seem to be working. It splits the photo but not in an exact way (you can try it).


Solution

  • from PIL import Image
    
    def crop(path, input, height, width, k, page, area):
        im = Image.open(input)
        imgwidth, imgheight = im.size
        for i in range(0,imgheight,height):
            for j in range(0,imgwidth,width):
                box = (j, i, j+width, i+height)
                a = im.crop(box)
                try:
                    o = a.crop(area)
                    o.save(os.path.join(path,"PNG","%s" % page,"IMG-%s.png" % k))
                except:
                    pass
                k +=1