Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble using python PIL library to crop and save image

People also ask

How do I crop an image using Python PIL?

The crop() function of the image class in Pillow requires the portion to be cropped as rectangle. The rectangle portion to be cropped from an image is specified as a four-element tuple and returns the rectangle portion of the image that has been cropped as an image Object.

How do I save a PIL library image?

Saving an image can be achieved by using . save() method with PIL library's Image module in Python.


The box is (left, upper, right, lower) so maybe you meant (2407, 804, 2407+71, 804+796)?

Edit: All four coordinates are measured from the top/left corner, and describe the distance from that corner to the left edge, top edge, right edge and bottom edge.

Your code should look like this, to get a 300x200 area from position 2407,804:

left = 2407
top = 804
width = 300
height = 200
box = (left, top, left+width, top+height)
area = img.crop(box)

Try this:

it's a simple code to crop an image, and it works like a charm ;)

import Image

def crop_image(input_image, output_image, start_x, start_y, width, height):
    """Pass input name image, output name image, x coordinate to start croping, y coordinate to start croping, width to crop, height to crop """
    input_img = Image.open(input_image)
    box = (start_x, start_y, start_x + width, start_y + height)
    output_img = input_img.crop(box)
    output_img.save(output_image +".png")

def main():
    crop_image("Input.png","output", 0, 0, 1280, 399)

if __name__ == '__main__': main()

In this case the Input image is 1280 x 800 px and the croped is 1280 x 399px starting at the top left corner.