python图像切割成多边形_使用Python / PIL的多边形裁剪/剪辑

The polygon points along with the uncut, original image are sent by client to the server.

Is there a way that I can clip (crop) the original image along these points in Python server, and save the cropped image?

I am currently using PIL, and would prefer a PIL or PIL extended solution.

Thanks in advance

解决方案

I found a solution using numpy and PIL- so thought I will share:

import numpy

from PIL import Image, ImageDraw

# read image as RGB and add alpha (transparency)

im = Image.open("crop.jpg").convert("RGBA")

# convert to numpy (for convenience)

imArray = numpy.asarray(im)

# create mask

polygon = [(444,203),(623,243),(691,177),(581,26),(482,42)]

maskIm = Image.new('L', (imArray.shape[1], imArray.shape[0]), 0)

ImageDraw.Draw(maskIm).polygon(polygon, outline=1, fill=1)

mask = numpy.array(maskIm)

# 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("out.png")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值