-1

我需要制作一个从红色到白色的 256 种颜色的颜色图,并在 Python 中显示红色通道,但看起来这件事做错了,我不明白为什么。这是我的代码:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

# How to create an array filled with zeros
img = np.zeros([256,256])
colormap1 = np.zeros([256,1])
#image:
for i in range(256):
    img[:,i] = i #on all columns I have the same value
    #to go from red to white we'll have: [1,0,0]...,[1,0.5,0.5],..[1,1,1]
for i in range(128):
    colormap1[i,1] = i/127     

#display the thing:  
colormap1 = mpl.colors.ListedColormap(colormap1)
plt.figure(), plt.imshow(img, cmap = colormap1)
4

1 回答 1

2

你可以这样回答:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

# How to create an array filled with zeros
img = np.zeros([256,256])
colormap = np.zeros([256,3])

#image:
for i in range(256):
    img[:,i] = i #on all columns I have the same value
    
#color map:
for i in range(256):
    colormap[i,0] = 1
    colormap[i,1] = (i+1)/256
    colormap[i,2] = (i+1)/256
    
#display the thing:
colormap = mpl.colors.ListedColormap(colormap)
plt.figure(), plt.imshow(img, cmap = colormap)

几乎就像你在这里所做的那样Colormap 它不是由正确的颜色组成的。您只需要编写代码的第二部分(从红色到白色)并在 256 步而不是 128 步中完成。

于 2020-10-23T13:45:05.290 回答