You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

图片圆形裁剪后保存遇KeyError问题求助

问题解决:图片圆形裁剪保存时的KeyError错误

错误原因

你遇到的KeyError: ((1, 1, 5), '|u1')是因为:

  1. 宽高赋值错误:PIL图像的size属性返回的是(宽度, 高度),你写的height,width = img.size搞反了尺寸,导致后续遮罩和原图像尺寸不匹配
  2. 使用np.dstack堆叠通道后生成了5通道数组(原图像如果是RGBA为4通道,加上遮罩的1通道),而PIL的Image.fromarray不支持这种非标准的5通道格式,因此抛出错误

修正方案

方案一:直接使用PIL内置方法(推荐,更简洁)

不需要转numpy数组,直接用PIL的putalpha方法将圆形遮罩作为透明通道合并到原图像:

from PIL import Image, ImageDraw

# 打开目标图像
img = Image.open(f"IMG/{thumb[0]}_{thumb[1]}x{thumb[1]}.png")
# 正确获取图像宽高
width, height = img.size

# 创建圆形遮罩(单通道灰度图,黑色为透明,白色为不透明)
lum_img = Image.new('L', (width, height), 0)
draw = ImageDraw.Draw(lum_img)
# 绘制完整圆形填充白色
draw.pieslice([(0, 0), (width, height)], 0, 360, fill=255)

# 将原图像转为RGBA模式(确保支持透明通道)
img_rgba = img.convert("RGBA")
# 把遮罩设置为图像的Alpha通道
img_rgba.putalpha(lum_img)

# 保存处理后的圆形图像
img_rgba.save("filename.png")

方案二:基于numpy数组处理

如果坚持使用numpy操作,需要确保最终生成的是PIL支持的4通道RGBA数组:

from PIL import Image, ImageDraw
import numpy as np

img = Image.open(f"IMG/{thumb[0]}_{thumb[1]}x{thumb[1]}.png")
width, height = img.size

lum_img = Image.new('L', (width, height), 0)
draw = ImageDraw.Draw(lum_img)
draw.pieslice([(0, 0), (width, height)], 0, 360, fill=255)

# 将原图像转为RGBA格式的numpy数组(4通道)
img_arr = np.array(img.convert("RGBA"))
# 将遮罩数组替换到RGBA的Alpha通道(第4个通道)
img_arr[:, :, 3] = np.array(lum_img)

# 从数组转回PIL图像并保存
im = Image.fromarray(img_arr)
im.save("filename.png")

内容的提问来源于stack exchange,提问作者FlyPhoenix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:56:13