Reputation: 520
This is a very rudimentary question and I'm sure that there's some part of the Pillow library/documentation I've missed...
Let's say you have a 128x128 image, and you want to save the "chunk" of it that is "x" pixels right from the top-left corner of the original image, and "y" pixels down from the top left corner of the original image (so the top left corner of this "chunk" is located at (x,y). If you know that the chunk you want is "a" pixels wide and "b" pixels tall (so the four corners of the chunk you want are known, and they're (x,y),(x+a,y),(x,y+b),(x+a,y+b)) - how would you save this "chunk" of the original image you're given as a separate image file?
More concisely, how can I save pieces of images given their pixel-coordinates using PIL? any help/pointers are appreciated.
Upvotes: 1
Views: 1337
Reputation: 520
Came up with:
"""
The function "crop" takes in large_img, small_img, x, y, w, h and returns the image lying within these restraints:
large_img: the filename of the large image
small_img: the desired filename of the smaller "sub-image"
x: x coordinate of the upper left corner of the bounding box
y: y coordinate of the upper left corner of the bounding box
w: width of the bounding box
h: height of the bounding box
"""
def crop(large_img, small_img, x, y, w, h):
img = Image.open(large_img)
box = (x, y, x+w, y+h)
area = img.crop(box)
area.save(small_img, 'jpeg')
Upvotes: 3