seb*_*seb 5 python crop path image-processing python-imaging-library
有没有办法用Python PIL 剪切图像的非矩形区域?
例如,在这张照片中,我想排除所有黑色区域以及塔楼,屋顶和杆子.
http://img153.imageshack.us/img153/5330/skybig.jpg
我想ImagePath模块可以做到这一点,但此外,我如何读取例如svg文件的数据并将其转换为路径?
任何帮助将不胜感激.
(我的子问题可能是更容易的任务:如何至少切割一个图像的圆圈?)
如果我理解正确,您希望在图像中使某些区域透明.这些区域是随机形状的.最简单的方法(我能想到的)是创建一个蒙版并将其放到图像的alpha通道.下面的代码显示了如何执行此操作.
如果您的问题是"如何创建多边形蒙版",我将重定向到:
看看接受的答案.
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")
Run Code Online (Sandbox Code Playgroud)
编辑
实际上,我无法抗拒......多边形蒙版解决方案非常优雅(用这个代替上面的圆圈):
# 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)
Run Code Online (Sandbox Code Playgroud)
EDIT2
现在,当我想到它.如果你有一个黑色和白色的svg,你可以直接加载你的svg作为面具(假设白色是你的面具).我没有样本svg图像,所以我无法测试这个.我不确定PIL是否可以打开svg图像.
| 归档时间: |
|
| 查看次数: |
4352 次 |
| 最近记录: |