我有一个包含值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()
# ------------------------------------------------------------
关于python - 用红色或黑色像素替换2D矩阵值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48669719/