首页 > 解决方案 > 使用python以圆形方式裁剪图像

问题描述

我想创建一个以循环方式裁剪图像的脚本。

我有一个接收各种图片(大小相同)的服务器,我希望服务器裁剪接收到的图像。

例如,转动这个图像:

前

进入这个:

后

我希望能够将其保存为 PNG(具有透明背景)。

如何才能做到这一点?

标签: pythonimage-processing

解决方案


这是一种方法:

#!/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')

在此处输入图像描述


推荐阅读