2010-09-14 29 views
4

有沒有辦法去掉使用Python PIL的圖像的矩形區域?用Python/PIL修剪圖像的非對稱區域

例如在這幅圖中,我想排除所有黑色區域以及塔樓,屋頂和柱子。
http://img153.imageshack.us/img153/5330/skybig.jpg

我想的ImagePath模塊可以做到這一點,而且此外,我怎樣才能讀取的例如數據一個SVG文件並將其轉換爲路徑?

任何幫助將不勝感激。


(我的子問題是大概是容易的任務:如何將至少削減圖像的圓)

+1

在該示例中,沒有複雜的計算機視覺方法,將無法以編程方式刪除塔樓,屋頂和柱子。你最好的選擇就是親自去做。而你的意思是什麼排除黑色區域?數字圖像是矩形 - 你想讓它們透明嗎? 就ImagePath而言,Path只是從座標列表創建的,我相信你可以從SVG文件中用一些python SVG庫獲取這些信息。 – 2010-09-20 20:31:45

+0

要做所有你問的,PIL是不夠的,因爲它缺乏圖像處理的基本工具。如果給出足夠的時間,你可以用Python自己構建它們,但是,考慮到問題的措辭,我懷疑你會遇到麻煩。我能給出的唯一幫助就是指出你需要更好地理解你的問題,並且一次只問一個問題。 – mmgp 2013-01-14 01:55:19

回答

4

如果我理解正確的,你想使一些區域的圖像內透明。而這些區域是隨機形狀的。 (我能想到的)最簡單的方法是創建一個蒙版並將其放置到圖像的Alpha通道。以下是顯示如何執行此操作的代碼。

如果你的問題是:「如何創建一個多邊形面具」我將您重定向到:

SciPy Create 2D Polygon Mask

,並期待接受的答案。

BR,

尤哈

import numpy 
import Image 

# read image as RGB and add alpha (transparency) 
im = Image.open("lena.png").convert("RGBA") 

# convert to numpy (for convenience) 
imArray = numpy.asarray(im) 

# create mask (zeros + circle with ones) 
center = (200,200) 
radius = 100 
mask = numpy.zeros((imArray.shape[0],imArray.shape[1])) 
for i in range(imArray.shape[0]): 
    for j in range(imArray.shape[1]): 
     if (i-center[0])**2 + (j-center[0])**2 < radius**2: 
      mask[i,j] = 1 

# assemble new image (uint8: 0-255) 
newImArray = numpy.empty(imArray.shape,dtype='uint8') 

# colors (three first columns, RGB) 
newImArray[:,:,:3] = imArray[:,:,:3] 

# transparency (4th column) 
newImArray[:,:,3] = mask*255   

# back to Image from numpy 
newIm = Image.fromarray(newImArray, "RGBA") 
newIm.save("lena3.png") 

編輯

其實,我忍不住......在多邊形面具的解決方案是如此優雅(替換這個上面圓圈):

# create mask 
polygon = [(100,100), (200,100), (150,150)] 
maskIm = Image.new('L', (imArray.shape[0], imArray.shape[1]), 0) 
ImageDraw.Draw(maskIm).polygon(polygon, outline=1, fill=1) 
mask = numpy.array(maskIm) 

編輯2

現在當我想起它。如果你有一個黑色和白色的SVG,你可以直接加載你的SVG作爲面具(假設白色是你的面具)。我沒有樣本svg圖像,所以我無法測試這個。我不確定PIL是否可以打開svg圖像。