用Python以圆形方式裁剪图像

11
我想创建一个脚本,以圆形方式裁剪图像。我有一个服务器,接收各种图片(大小相同),我希望服务器能够裁剪所接收到的图像。例如,将这张图片:Before 裁剪成这样:After。我希望能将其保存为PNG格式(带有透明背景)。如何实现呢?

这里甚至没有真正具体的要求,更别提任何特定的问题了。 - Mad Physicist
使用Pillow在黑色背景上绘制一个白色圆圈,并将其作为额外通道添加,然后保存。 - Mark Setchell
这不是裁剪,而是基本的遮罩。您可以制作一个圆形遮罩并将其用作 alpha 通道。 - user8190410
1个回答

21

这是一种解决方法:

#!/usr/local/bin/python3
import numpy as np
from PIL import Image, ImageDraw

# Open the input image as numpy array, convert to RGB
img=Image.open("dog.jpg").convert("RGB")
npImage=np.array(img)
h,w=img.size

# Create same size alpha layer with circle
alpha = Image.new('L', img.size,0)
draw = ImageDraw.Draw(alpha)
draw.pieslice([0,0,h,w],0,360,fill=255)

# Convert alpha Image to numpy array
npAlpha=np.array(alpha)

# Add alpha layer to RGB
npImage=np.dstack((npImage,npAlpha))

# Save with alpha
Image.fromarray(npImage).save('result.png')

输入图像描述


1
在代码行Image.fromarray(npImage).save('result.png')draw.pieslice([0,0,h,w],0,360,fill=255)中,我遇到了错误Cannot handle this data type: (1, 1, 5), |u1。我不得不通过draw.pieslice(((0, 0), (h, w)), 0, 360, fill=255)进行更新。 - alambertt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接