2017-05-31 70 views
1

這是一個非常基本的問題,我敢肯定,有枕頭庫/文件我已經錯過了一些局部圖像的「塊」 ......返回使用Python和枕頭

比方說,你有一個128x128圖像,並且您想要將原始圖像左上角的「x」像素的「塊」保存起來,並將原始圖像左上角的「y」像素向下保存(所以這個「塊」的左上角位於(x,y)。如果你知道你想要的塊是「a」像素寬和「b」像素高(所以你想要的塊的四個角是已知的,它們是(x,y),(x + a,y),(x,y + b),(x + a,y + b)) - 你將如何保存原始圖像的這個「塊」 '作爲單獨的圖像文件給出?

更簡潔些,我如何使用PIL給出像素座標的圖像片段?任何幫助/指針表示讚賞。

+0

怎麼樣[的文檔的這部分(http://pillow.readthedocs.io/en/3.1.x/handbook/tutorial.html#cutting-pasting-和合並圖像)?我假設,這個子圖像在內部與其他圖像相同,並且可以放入可用的IO函數中。 (但是我從來沒有使用過這個lib;我喜歡scikit-image,但是我認爲它是一個更重的依賴) – sascha

回答

2

趕上了:

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