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

2024-10-01 11:28:47 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以用Python-PIL剪切出图像中矩形区域?在

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

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

任何帮助都将不胜感激。



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


Tags: 方法图像http区域pil图片jpgus
1条回答
网友
1楼 · 发布于 2024-10-01 11:28:47

如果我理解正确的话,你想让图像中的某些区域透明。这些区域是随机形状的。最简单的方法(我能想到的)是创建一个遮罩,并将其放入图像的alpha通道。下面是一个代码,展示了如何做到这一点。在

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

SciPy Create 2D Polygon Mask

看看公认的答案。在

比尔

朱哈

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")

编辑

事实上,我无法抗拒。。。多边形遮罩解决方案非常优雅(用这个代替上面的圆圈):

^{pr2}$

编辑2

现在我想起来了。如果您有一个黑白svg,您可以直接加载svg作为掩码(假设白色是您的掩码)。我没有svg图像的示例,所以我无法测试它。我不确定PIL是否可以打开svg图像。在

相关问题 更多 >