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

使用PIL库paste方法触发TypeError:color参数类型错误求助

问题分析与解决

错误根源

  1. ImageOps.colorize参数不匹配:digit_rotated是单通道灰度图("L"模式),该函数针对单通道图的颜色参数应传入单值整数或单元素元组,而非三通道RGB元组。
  2. paste方法调用错误:需调用目标画布实例的paste方法,而非直接调用Image.Image类的方法。

修正后的代码

import cv2
import PIL
from PIL import Image
from PIL import ImageFont, ImageDraw, ImageOps
import numpy as np
import random

def generate_new(text: str="") -> Image.Image:
    # 初始化浅灰色背景的验证码画布
    captcha = Image.fromarray(243*np.ones(shape=[30,100,3], dtype=np.uint8))
    font_path = "/content/drive/MyDrive/captchas/qwerty.ttf"
    font = ImageFont.truetype(font_path, 22)
    
    x = 10
    for symbol in text:
        # 创建单通道画布绘制单个字符
        digit = Image.new("L",(30,30))
        cursor = ImageDraw.Draw(digit)
        cursor.text((10, 0), symbol, font=font, fill=255)
        
        # 随机旋转字符
        digit_rotated = digit.rotate(random.randrange(-70,70), PIL.Image.NEAREST, expand=0)
        
        # 灰度图转RGB:使用单值颜色参数匹配通道数
        colored_digit = ImageOps.colorize(digit_rotated, 0, 255)
        # 粘贴到验证码画布,以旋转后的灰度图为蒙版
        captcha.paste(colored_digit, (x,6), digit_rotated)
        x += 25  # 调整间距避免旋转后字符重叠
    
    return captcha

captcha = generate_new("12345")
captcha.save("/content/drive/MyDrive/captchas/12345.png")

关键修正说明

  • 颜色参数调整:将(0,0,0)和(255,255,255)改为0和255,适配单通道图像的颜色要求。
  • 方法调用修正:把Image.Image.paste(...)改为captcha.paste(...),确保操作作用在目标画布实例上。
  • 字符间距优化:调整x的步长为25,避免旋转后的字符互相遮挡。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 17:40:24