Skip to content

Instantly share code, notes, and snippets.

@jss367
Created October 24, 2017 15:36
Show Gist options
  • Save jss367/01aa847d5997e1d9acc2a4846d1827ce to your computer and use it in GitHub Desktop.
Save jss367/01aa847d5997e1d9acc2a4846d1827ce to your computer and use it in GitHub Desktop.
Convert an RGB image to grayscale
def grayscale(image, algorithm='luminosity'):
"""
The algorithms are based on those used in GIMP. They are 'lightness', 'average', and 'luminosity'. Luminosity is the default
"""
l, w, color_space = image.shape
num_pxls = l*w
assert (color_space == 3), "The image must have three dimensions of color: red, green, and blue"
# Extract the individual colors
red = image[:,:,0]
green = image[:,:,1]
blue = image[:,:,2]
# Flatten each color's image to make it easier to work with
if algorithm == 'luminosity':
gray = 0.21 * red + 0.72 * green + 0.07 * blue
return gray
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment