python - 使用python以圆形方式裁剪图像
问题描述
我想创建一个以循环方式裁剪图像的脚本。
我有一个接收各种图片(大小相同)的服务器,我希望服务器裁剪接收到的图像。
例如,转动这个图像:
进入这个:
我希望能够将其保存为 PNG(具有透明背景)。
如何才能做到这一点?
解决方案
这是一种方法:
#!/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')
推荐阅读
- amazon-web-services - 如何使用 hdockerpy 和 aws ecr repo 修复没有基本身份验证凭据错误?
- php - httpd.conf 中可能有语法错误
- python - 在 sagemaker 上的 tensorflow 上接收错误作为输入必须是一个向量,得到形状:[1,2]
- excel - VBA 在 Microsoft Word 中工作正常,但在 Libre Office 作家中无法工作如何修复
- c++ - 运行时动态函数解析
- c# - 无法从字符串转换为 Microsft.AspNetCore.Http.IFormFile
- python - 当我在 VS 代码中运行 python notebook 时,是否有任何解决 URL 错误的方法?
- javascript - 从 Google Trends API 获取数据但收到意外的令牌错误
- git - git stash pop 自动合并后如何找回丢失的代码?
- python-3.x - 双循环:while循环中的for循环