use*_*409 6 python python-imaging-library
多边形点与未切割的原始图像一起由客户端发送到服务器.
有没有办法可以在Python服务器中沿着这些点剪切(裁剪)原始图像,并保存裁剪后的图像?我目前正在使用PIL,并且更喜欢PIL或PIL扩展解决方案.
提前致谢
use*_*409 17
我找到了使用numpy和PIL的解决方案 - 所以我想分享:
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")
Run Code Online (Sandbox Code Playgroud)
小智 7
我编写了这段代码来剪辑由多边形定义的图像区域。
from PIL import Image, ImageDraw
original = Image.open("original.jpg")
xy = [(100,100),(1000,100),(1000,800),(100,800)]
mask = Image.new("L", original.size, 0)
draw = ImageDraw.Draw(mask)
draw.polygon(xy, fill=255, outline=None)
black = Image.new("L", original.size, 0)
result = Image.composite(original, black, mask)
result.save("result.jpg")
Run Code Online (Sandbox Code Playgroud)