首页 > 解决方案 > 覆盖numpy数组中的像素

问题描述

我有一张图像,我试图用一些任意颜色(比如说蓝色)替换像素。我怎样才能用数组做到这一点。例如我的图像是:

a b c d e
f g h i j
k l m n o
p q r s t
u v w x y

我想改变列 3,2,3,4,3 的颜色,这样我的图像就变成了

a b c * e
f g * i j
k l m * o
p q r s *
u v w * y

其中 * 是用蓝色替换的像素。怎么可能做到这一点?

标签: pythonnumpyimage-processing

解决方案


由于您没有指定任何限制,我认为任何工具都可以,所以我建议使用Pillow。(安装pip install Pillow

假设您的图像已命名image.png,那么您可以遍历要编辑的像素并将每个位置的颜色设置为所需的颜色。

from PIL import Image

replacement_color = (0, 0, 255)
columns = [3, 2, 3, 4, 3]
positions = [(x, y) for y, x in enumerate(columns)]

image = Image.open('image.png')
pixels = image.load()

for (x, y) in positions:
    pixels[x, y] = replacement_color

image.show() # or image.save('transformed_image.png')

请注意,这是访问和编辑单个像素的方法可能非常慢。


编辑:

使用布尔 numpy 数组作为掩码来识别您也可以使用的正确像素

import numpy as np
from PIL import Image

image = Image.open('image.png')
image_array = np.array(image)

# Just an example mask
diagonal = np.eye(image_array.shape[0], image_array.shape[1])
mask = diagonal == 1

image_array[mask] = [0, 0, 255, 0] # RGBA

altered_image = Image.fromarray(image_array)
altered_image.save('altered_image.png')

(改编自本指南

我不确定,如果性能更好。


推荐阅读