首页 > 解决方案 > draw rgb spectrum in python/numpy

问题描述

I'm new to Python and i need to draw a RGB spectrum as a numpy array. For me it's clear that i need to rise the RGB values across the dimensions to get the spectrum.

import numpy as np
import matplotlib.pyplot as plt 

spectrum = np.zeros([255,255, 3], dtype=np.unit8) #init the array
#fill the array with rgb values to create the spectrum without the use of loops

plt.imshow(spectrum)
plt.axis('off')  # don't show axis
plt.show()

Is there a possiblity (e.g. a python or numpy method) to create the spectrum without the use of loops?

标签: pythonnumpy

解决方案


Not sure if this is the result you'd like, but you could define the arrays for the RGB values yourself (see HSV-RGB comparison). I've used Pillow to convert grayscale to colour.

import numpy as np
import matplotlib.pyplot as plt 
from PIL import Image
spectrum = np.zeros([256,256*6, 3], dtype=np.uint8) # init the array
# fill the array with rgb values to create the spectrum without the use of loops
spectrum[:,:,0] = np.concatenate(([255]*256, np.linspace(255,0,256), [0]*256, [0]*256, np.linspace(0,255,256), [255]*256), axis=0)
spectrum[:,:,1] = np.concatenate((np.linspace(0,255,256), [255]*256, [255]*256, np.linspace(255,0,256), [0]*256,[0]*256), axis=0)
spectrum[:,:,2] = np.concatenate(([0]*256, [0]*256,np.linspace(0,255,256),[255]*256, [255]*256, np.linspace(255,0,256)), axis=0)
img = Image.fromarray(spectrum, 'RGB')
img.show()

推荐阅读