繁体   English   中英

使用Python / PIL裁剪图像的非对称区域

[英]Crop non symmetric area of an image with Python/PIL

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

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

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

任何帮助将不胜感激。


(我的子问题可能是更容易的任务:如何至少切割一个图像的圆圈?)

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

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

SciPy创建2D多边形蒙版

看看接受的答案。

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)

EDIT2

现在,当我想到它。 如果你有一个黑色和白色的svg,你可以直接加载你的svg作为面具(假设白色是你的面具)。 我没有样本svg图像,所以我无法测试这个。 我不确定PIL是否可以打开svg图像。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM