使用Python/PIL的多边形裁剪/剪辑 [英] Polygon crop/clip using Python / PIL
本文介绍了使用Python/PIL的多边形裁剪/剪辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
多边形点与未切割的原始图像一起由客户端发送到服务器.
The polygon points along with the uncut, original image are sent by client to the server.
有没有一种方法可以沿着这些点在Python服务器中裁剪(裁剪)原始图像,并保存裁剪后的图像? 我目前正在使用PIL,并且希望使用PIL或PIL扩展解决方案.
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.
预先感谢
推荐答案
我找到了一个使用numpy和PIL的解决方案,因此我想与大家分享:
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")
这篇关于使用Python/PIL的多边形裁剪/剪辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文