Thursday, May 31, 2018

How to Calculate RGB Percent Using Python

I was working on a project recently, where marketing needed varying shades of the same color for an online map.  So, my boss and I wrote a python script that will give the RGB numbers for your input.

Using PyScriptor, this was my code:


def main():
    pass

if __name__ == '__main__':
    main()

import numpy as np
import arcpy

#This script will calculate a percentage of a RGB color.

red = arcpy.GetParameterAsText(0)
green = arcpy.GetParameterAsText(1)
blue = arcpy.GetParameterAsText(2)

percent = arcpy.GetParameterAsText(3)

rgb = [int(red),int(green),int(blue)]
pct = float(percent)

def lighter(color, percent):
    '''assumes color is rgb between (0, 0, 0) and (255, 255, 255)'''
    color = np.array(color)
    white = np.array([255, 255, 255])
    vector = white-color
    return color + vector * percent
arcpy.AddMessage(lighter(rgb, pct))


Load this script into your ArcToolbox in ArcMap, and then it can be used in any mxd.  When running, it will ask for your RGB and the percent that you want.

Here is a post about how to calculate sequential numbers in ArcMap using Field Calculator.

Happy GISing!
Lindsy Hales Bentley