How do I increase/decrease color saturation of an image using Jython (JES)?

1.7k views Asked by At

I am trying to create a pair of functions that will increase or decrease the overall color saturation of an image. I understand that "saturation" essentially means "further from or closer to gray", so I need to either increase or decrease the RGB channels, but I can't do them all equally (i.e., r * 2, g * 2, b * 2) since that just makes the image lighter.

I was trying to use the formulae given here: http://www.georeference.org/doc/colors_as_hue_saturation_and_brightness.htm but when I tried to use it in my code, the image is almost entirely black, with some spots of yellow.

Here is what I've tried so far:

def upSaturation(pictu):
   '''Takes a picture and increases the overall color saturation'''
   satuP = duplicatePicture(pictu)
   for pixel in getPixels(satuP):
   r = getRed(pixel)
   g = getGreen(pixel)
   b = getBlue(pixel)
   mn = min(r, g, b)
   mx = max(r, g, b)
   lht = (mx + mn) / 2
   if lht <= 128:
     satu = 255 * ((mx - mn) / (mx + mn))
     clr = makeColor(r * satu, g * satu, b * satu)
     setColor(pixel, clr)
   else:
     sat = 255 * ((mx - mn) / (511 - (mx + mn)))
     color = makeColor(r * sat, g * sat, b * sat)
     setColor(pixel, color)
 show(satuP)
 return satuP

I also tried just having makeColor(sat, sat, sat) but that one came out entirely black with some spots of white. I'm not sure what else to do at this point. I would greatly appreciate some guidance.

1

There are 1 answers

0
super_mario3d On BEST ANSWER

To increase saturation you have to increase the value of the primary colour. If for example the pixel is mainly red you have to increase the red content of the pixel and reduce the rest.

def upSaturation(pictu): 
'''Takes a picture and increases the overall color saturation'''
 satuP = duplicatePicture(pictu)
 for pixel in getPixels(satuP):
  r = getRed(pixel)
  g = getGreen(pixel)
  b = getBlue(pixel)
  # check if red is primary colour
  if r > g and r > b:
   # Saturate with red
   r = r + 5
   if g < b:
     g = g - 5
   else:
     b = b - 5

  # check if green is primary colour
  if g > r and g > b:
   # Saturate with green
   g = g + 5
   if r < b:
     r = r - 5
   else:
     b = b - 5

  # check if blue is primary colour
  if b > r and b > g:
   # Saturate with blue
   b = b + 5
   if r < g:
     r = r - 5
   else:
     g = g - 5

 color = makeColor(r, g, b)
 setColor(pixel, color)
 explore(satuP)
 return satuP