7

我想通過切割邊界上的白色區域來將圖像裁剪爲較小的尺寸。我嘗試了在這個論壇中提出的解決方案Crop a PNG image to its minimum size,但是pil的getbbox()方法返回了一個尺寸相同的圖像的邊界框,也就是說,它似乎不能識別周圍的空白區域。我嘗試了以下內容:python圖像庫(PIL)中的getbbox方法不起作用

>>>import Image 
>>>im=Image.open("myfile.png") 
>>>print im.format, im.size, im.mode 
>>>print im.getbbox() 
PNG (2400,1800) RGBA 
(0,0,2400,1800) 

我通過使用GIMP自動裁剪裁剪圖像來檢查我的圖像是否具有真正的白色裁剪邊框。我也試過用ps和eps版本的圖,沒有運氣。
任何幫助將不勝感激。

回答

16

麻煩是getbbox()作物脫離黑色邊界,從文檔:Calculates the bounding box of the non-zero regions in the image

enter image description hereenter image description here

import Image  
im=Image.open("flowers_white_border.jpg") 
print im.format, im.size, im.mode 
print im.getbbox() 
# white border output: 
JPEG (300, 225) RGB 
(0, 0, 300, 225) 

im=Image.open("flowers_black_border.jpg") 
print im.format, im.size, im.mode 
print im.getbbox() 
# black border output: 
JPEG (300, 225) RGB 
(16, 16, 288, 216) # cropped as desired 

我們可以爲白色邊框做一個簡單的辦法,通過第一反轉使用ImageOps.invert的圖像,然後使用getbbox()

import ImageOps 
im=Image.open("flowers_white_border.jpg") 
invert_im = ImageOps.invert(im) 
print invert_im.getbbox() 
# output: 
(16, 16, 288, 216) 
+3

謝謝你很多關於快速和明確的迴應。它的工作原理,但我必須在使用反轉之前先將RGBA轉換爲RGB,方法是調用convert:invert_im = im.convert(「RGB」),然後invert_im = ImageOps.invert(invert_im),否則我得到一個IOError「不支持此圖像模式「。 – etepoc 2012-03-26 16:12:22

+0

@ user1292774 - 很酷,很高興它的工作..,如果你喜歡,你可以upvote /並勾選箭頭接受答案,在左上角,然後我們都得到了一些點;) – fraxel 2012-03-26 16:18:10

+0

我已經嘗試upvote,但我有不到15分,系統暫時不讓我,如果我得到那15分,我會做。謝謝! – etepoc 2012-03-26 16:24:28