2010-09-14 62 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图像。