python - 用红色或黑色像素替换2D矩阵值

标签 python numpy opencv scipy python-imaging-library

我有一个包含值0、200和500的大2D矩阵,我需要用红色像素替换200,用黑色像素替换500,用白色像素替换0

最佳答案

这样做并不难。
我假设您拥有的数组是一个numpy数组。
我在下面使用了python3。
希望这可以帮助。

import random
import numpy as np
from PIL import Image

#----------- (Your Array of 500s, 200s and 0s)------------
a = np.random.randint(3, size=(500, 500))
a[a==2] = 500
a[a==1] = 200
# --------------------------------------------------------

# ----------- Code which you need to run ----------------------------
R, G, B = np.zeros(a.shape), np.zeros(a.shape), np.zeros(a.shape)
R[a==200], G[a==200], B[a==200] = 255, 0, 0
R[a==500], G[a==500], B[a==500] = 0, 0, 0
R[a==0], G[a==0], B[a==0] = 255, 255, 255
R, G, B = Image.fromarray(R.astype('uint8'),mode=None), Image.fromarray(G.astype('uint8'),mode=None), Image.fromarray(B.astype('uint8'),mode=None) 
merged=Image.merge("RGB",(R,G,B))

merged.show()
# ------------------------------------------------------------

Output of the above code

关于python - 用红色或黑色像素替换2D矩阵值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48669719/

相关文章:

python - C++ - 无法编译 OpenCV 程序

python / NumPy : Convert list of bools to unsigned int

python-3.x - Python 中的缺失值插补

python - np.linalg.qr(A) 或 scipy.linalg.orth(A) 用于查找正交基(python)

c++ - 是否可以使用opencv的imshow在没有工具栏的情况下显示图像?

python - 如何获得带孔的二进制掩码的边界坐标?

python - Django rq 的 Supervisord 配置不起作用

python - 为什么 tkinter 按钮的高度选项在 OSX 和 Windows 上的行为不同?

Python shell 由于递归深度而重新启动

opencv - 浮点矩阵OpenCV中的缺失值