python - 覆盖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
其中 * 是用蓝色替换的像素。怎么可能做到这一点?
解决方案
由于您没有指定任何限制,我认为任何工具都可以,所以我建议使用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')
(改编自本指南)
我不确定,如果性能更好。
推荐阅读
- c# - 检测机器人应用程序打开事件
- html - Bg视频不能在iphone上播放,以前用过
- javascript - 为什么我的子类不从 Javascript 中的父类继承属性?
- windows - 设置 NMake Makefile 目录
- vue.js - 如何在 vue js 中对齐 Integer 值?
- apache-poi - 如何在 Excel Apache POI 中以两位小数设置单元格宽度
- swift - 错误域=NSCocoaErrorDomain 代码=4099
- java - android.database.sqlite.SQLiteException:没有这样的列:bucket_display_name
- android - 在地图视图android上添加视图覆盖
- python - 我的数据集应该是一个大括号集/字典时显示一个字符串