5

有没有办法用 Python PIL 切出图像的矩形区域?

例如,在这张图片中,我想排除所有黑色区域以及塔、屋顶和电线杆。
http://img153.imageshack.us/img153/5330/skybig.jpg

我想ImagePath模块可以做到这一点,但此外,我怎样才能读取例如 svg 文件的数据并将其转换为路径?

任何帮助将不胜感激。


(我的子问题大概是更简单的任务:如何切割至少一圈图像?)

4

1 回答 1

8

如果我理解正确,您想让图像中的某些区域透明。这些区域是随机形状的。最简单的方法(我能想到的)是创建一个蒙版并将其放入图像的 Alpha 通道。下面是显示如何执行此操作的代码。

如果您的问题是“如何创建多边形蒙版”,我会将您重定向到:

SciPy 创建 2D 多边形蒙版

并查看接受的答案。

兄弟,

朱哈

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 图像。

于 2011-03-25T22:05:35.880 回答