简体   繁体   English

使用Python和Pillow返回图像的“块”

[英]Returning “chunk” of Image using Python and Pillow

This is a very rudimentary question and I'm sure that there's some part of the Pillow library/documentation I've missed... 这是一个非常基本的问题,我敢肯定我错过了Pillow库/文档的某些部分...

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? 假设您有一张128x128的图片,并且要保存其中的“块”,即从原始图片的左上角起为“ x”像素,而从图片的左上角起为“ y”像素原始图像(因此,该“块”的左上角位于(x,y)。如果您知道所需的块宽为“ a”像素,而“ b”高)(因此,该块的四个角您想要知道的,它们是(x,y),(x + a,y),(x,y + b),(x + a,y + b))-如何保存此“块”您获得的原始图像是作为单独的图像文件显示的?

More concisely, how can I save pieces of images given their pixel-coordinates using PIL? 简而言之,如何使用PIL保存图像的像素坐标? any help/pointers are appreciated. 任何帮助/指针表示赞赏。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM