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

如何在Krita中修改像素值:Python自定义反色脚本报错求解

Krita Python脚本像素修改报错解决方案

报错原因说明

  • 报错TypeError: 'QByteArray' object does not support item assignment:Krita接口返回的QByteArray属于不可变类型,不支持直接修改单个位置的元素
  • 报错ValueError: invalid literal for int() with base 10: b'\xff':从QByteArray中直接取出的元素是字节类型而非整数,无法直接参与数值运算

修改后的可运行代码

from krita import *

doc = Krita.instance().activeDocument()
width = doc.width()
height = doc.height()

current_layer = doc.activeNode()
# 将不可变的QByteArray转为Python原生可变bytearray
q_byte_data = current_layer.pixelData(0, 0, width, height)
pixel_data = bytearray(q_byte_data)

for x in range(width):
    for y in range(height):
        base_idx = 4 * (y * width + x)
        # 仅修改RGB三个通道,保留alpha通道不变
        for c in range(3):
            pixel_data[base_idx + c] = 0xff - pixel_data[base_idx + c]

# 转换回QByteArray后写回图层
current_layer.setPixelData(QByteArray(pixel_data), 0, 0, width, height)
doc.refreshProjection()

可选性能优化

处理大尺寸图层时三重循环效率较低,可引入numpy做向量化运算,速度提升明显:

from krita import *
import numpy as np

doc = Krita.instance().activeDocument()
width = doc.width()
height = doc.height()
current_layer = doc.activeNode()

# 直接将像素数据转为numpy uint8数组
pixel_data = np.frombuffer(current_layer.pixelData(0,0,width,height), dtype=np.uint8)
# 向量化反色RGB通道,alpha通道保持不变
pixel_data[0::4] = 255 - pixel_data[0::4]
pixel_data[1::4] = 255 - pixel_data[1::4]
pixel_data[2::4] = 255 - pixel_data[2::4]

current_layer.setPixelData(QByteArray(pixel_data.tobytes()), 0, 0, width, height)
doc.refreshProjection()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 13:54:02