简体   繁体   中英

create a color coded image from 2D array of angles

i am trying to write some code in python relating angles to a certain colors. basically i have a 2d array full of angles where i looped through other arrays to perform calculations to arrive at ha_deg for each pixel

ha_array[i,j] = ha_deg

and i want to turn this into an image with color gradients. so if 0 is red, 180 is green and 360 is blue, i will be able to go pixel by pixel to assign a color to each angle. sorry this is kind of an open ended question, I'm just not really sure how to proceed and could use some guidance! thank you!

Here's a way to do this. Below is a general function for generating linear RGB color gradients between two RGB values. By combining color gradients of the appropriate lengths from red to green and from green to blue, one can make a list of RGB color values that can serve as a map between your angle values and the desired colors:

def generateColorGradient(RGB1, RGB2, n, includeEnd=False):
    dRGB = [float(x2-x1)/(n-1) for x1, x2 in zip(RGB1, RGB2)]
    gradient = [tuple([int(x+k*dx) for x, dx in zip(RGB1, dRGB)]) for k in range(n-1+includeEnd)]
    return gradient

gradient1 = generateColorGradient((255, 0, 0), (0, 255, 0), 181, includeEnd=False)
gradient2 = generateColorGradient((0, 255, 0), (0, 0, 255), 181, includeEnd=True)

gradient = numpy.array(gradient1 + gradient2)

#If `ha_array` is a numpy array, you can simply do this to convert all angles to RGB values:

color_array = gradient[ha_array]

#Then if you're using PIL to make images:

image = Image.fromarray(numpy.uint8(color_array))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM