How to Split Image Into Multiple Pieces in Python

后端 未结 12 836
感动是毒
感动是毒 2020-12-01 00:27

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.siz         


        
12条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 00:42

    Here is a concise, pure-python solution that works in both python 3 and 2:

    from PIL import Image
    
    infile = '20190206-135938.1273.Easy8thRunnersHopefully.jpg'
    chopsize = 300
    
    img = Image.open(infile)
    width, height = img.size
    
    # Save Chops of original image
    for x0 in range(0, width, chopsize):
       for y0 in range(0, height, chopsize):
          box = (x0, y0,
                 x0+chopsize if x0+chopsize <  width else  width - 1,
                 y0+chopsize if y0+chopsize < height else height - 1)
          print('%s %s' % (infile, box))
          img.crop(box).save('zchop.%s.x%03d.y%03d.jpg' % (infile.replace('.jpg',''), x0, y0))
    

    Notes:

  • The crops that go over the right and bottom of the original image are adjusted to the original image limit and contain only the original pixels.
  • It's easy to choose a different chopsize for w and h by using two chopsize vars and replacing chopsize as appropriate in the code above.

提交回复
热议问题