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

如何用Python部分修改图像颜色?指定索引RGB修改出空白图求助

问题分析与修复

你的代码核心问题是错误地用np.delete处理像素数组来获取索引,np.delete(pixels, skip_indices, 0)返回的是删除指定索引后的像素值数组,不是你需要的索引列表,这直接导致后续赋值操作完全错误,最终生成空白图。

修正步骤

  • 先生成所有像素的索引数组
  • 从所有索引中排除skip_indices,得到需要修改的目标索引
  • 用正确的索引去修改对应位置的RGB值

修正后的完整代码

import numpy as np
from PIL import Image

target_image = Image.open("img.png")
target_image_array = np.array(target_image)
# 处理RGBA格式图片,转为RGB
if target_image_array.shape[-1] == 4:
    target_image_array = target_image_array[..., :3]
pixels = target_image_array.reshape(-1, 3)

skip_indices = np.arange(101_600, 254_000)
# 生成所有像素索引,排除skip_indices得到要修改的索引
all_indices = np.arange(pixels.shape[0])
indices_to_grey_out = np.setdiff1d(all_indices, skip_indices)

pixels_greyed_out = pixels.copy()
# 将指定索引的RGB设为0(纯黑,若要灰色可改为[127,127,127])
pixels_greyed_out[indices_to_grey_out] = [0, 0, 0]

pixels_greyed_out = pixels_greyed_out.reshape(target_image_array.shape)
modified_img = Image.fromarray(pixels_greyed_out)
modified_img.show()

额外说明:如果你的原图是带透明通道的RGBA格式,必须先转为RGB再处理,否则数组维度不匹配会导致后续操作出错,代码中已加入对应判断处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 20:12:13