Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 539
Elteroooo Avatar asked May 10 '11 16:05

Elteroooo


People also ask

How do you split a single image into multiple sections in Python?

Image. split() method is used to split the image into individual bands. This method returns a tuple of individual image bands from an image.


1 Answers

Edit: I believe this answer missed the intent to cut an image into rectangles in columns and rows. This answer cuts only into rows. It looks like other answers cut in columns and rows.

Simpler than all these is to use a wheel someone else invented :) It may be more involved to set up, but then it's a snap to use.

These instructions are for Windows 7; they may need to be adapted for other OSs.

Get and install pip from here.

Download the install archive, and extract it to your root Python installation directory. Open a console and type (if I recall correctly):

python get-pip.py install 

Then get and install the image_slicer module via pip, by entering the following command at the console:

python -m pip install image_slicer 

Copy the image you want to slice into the Python root directory, open a python shell (not the "command line"), and enter these commands:

import image_slicer image_slicer.slice('huge_test_image.png', 14) 

The beauty of this module is that it

  1. Is installed in python
  2. Can invoke an image split with two lines of code
  3. Accepts any even number as an image slice parameter (e.g. 14 in this example)
  4. Takes that parameter and automagically splits the given image into so many slices, and auto-saves the resultant numbered tiles in the same directory, and finally
  5. Has a function to stitch the image tiles back together (which I haven't yet tested); files apparently must be named after the convention which you will see in the split files after testing the image_slicer.slice function.
like image 67
Alex Hall Avatar answered Oct 09 '22 17:10

Alex Hall