简体   繁体   English

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

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

Is there a way to cut out non rectangular areas of an image with Python PIL? 有没有办法用Python PIL剪切图像的矩形区域?

eg in this picture I want to exclude all black areas as well as towers, rooftops and poles. 例如,在这张照片中,我想排除所有黑色区域以及塔楼,屋顶和杆子。
http://img153.imageshack.us/img153/5330/skybig.jpg http://img153.imageshack.us/img153/5330/skybig.jpg

I guess the ImagePath Module can do that, but furthermore, how can I read data of eg a svg file and convert it into a path? 我想ImagePath模块可以做到这一点,但此外,我如何读取例如svg文件的数据并将其转换为路径?

Any help will be appreciated. 任何帮助将不胜感激。


(My sub question is presumably the easier task: how to cut at least a circle of an image?) (我的子问题可能是更容易的任务:如何至少切割一个图像的圆圈?)

If I understood correctly, you want to make some areas transparent within the image. 如果我理解正确,您希望在图像中使某些区域透明。 And these areas are random shaped. 这些区域是随机形状的。 Easiest way (that I can think of) is to create a mask and put it to the alpha channel of the image. 最简单的方法(我能想到的)是创建一个蒙版并将其放到图像的alpha通道。 Below is a code that shows how to do this. 下面的代码显示了如何执行此操作。

If your question was "How to create a polygon mask" I will redirect you to: 如果您的问题是“如何创建多边形蒙版”,我将重定向到:

SciPy Create 2D Polygon Mask SciPy创建2D多边形蒙版

and look the accepted answer. 看看接受的答案。

br, BR,

Juha 尤哈

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

Edit 编辑

Actually, I could not resist... the polygon mask solution was so elegant (replace the above circle with this): 实际上,我无法抗拒......多边形蒙版解决方案非常优雅(用这个代替上面的圆圈):

# 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 EDIT2

Now when I think of it. 现在,当我想到它。 If you have a black and white svg, you can load your svg directly as mask (assuming white is your mask). 如果你有一个黑色和白色的svg,你可以直接加载你的svg作为面具(假设白色是你的面具)。 I have no sample svg images, so I cannot test this. 我没有样本svg图像,所以我无法测试这个。 I am not sure if PIL can open svg images. 我不确定PIL是否可以打开svg图像。

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

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