Saturday, December 24, 2011

Colorize image filter in Haskell

Problem
Recently I've been working on converting some image processing scripts from PHP (terrible for processing with lots of backing data) into Haskell (excellent when dealing with lots of backing data). The script I'm currently converting renders images that represent large amounts of GIS point data, with each point color coded by some attribute associated with the Point. The way I had achieved the color coding in PHP was by creating a greyscale "dot" image and the using PHP's IMG_FILTER_COLORIZE.
Greyscale point (left); Colorized points

Options
When I began exploring image processing and generation in Haskell, I discovered that my options were somewhat limited:
  • CV library - bindings for OpenCV. This seems like a powerful tool, but it has a number of external requirements, and seems to be a bit overkill for what I want. There is also HOpenCV, which seems fairly similar
  • Chalkboard - a really interesting/promising but now seemingly abandoned project started by the ITTC department of University of Kansas. It uses the concept that any geometric shape in 2D space can be achieved by creating unit shapes at the origin and then transforming them. Images are created as a blank "canvas" that can be manipulated programmatically and then displayed directly using the library's built in canvas viewer or by saving to a file
  • GD library - the winner, for my purposes. I needed something simple, solid, and flexible. The Haskell GD library uses the C GD library behind the scenes, which is the same backend that PHP uses for it's image processing functions. What GD has going for it is that it's familiar, and really really straightforward when it comes to creating simple images.
Once I had decided on using the GD library, I ran into an issue; the Haskell GD library doesn't support any image filters like PHP does, which means I would have no way to color code my points programmatically unless I was willing to replace my custom point marker with a regular old filled ellipse (boo!).  So the obvious solution was to write my own colorize filter.

Concepts for Colorize
Colorization is simply Color Addition; The algorithm is passed an image and a desired amount to add/subtract of RGB (-255 0 0 would represent a subtraction of all red, and no change for green and blue). Then for each pixel of the image, you do the passed RGB addition/subtraction. As you may have noticed, the range for the R, G, and B values that you pass in to the colorize filter is -255 to +255. This means that a colorize filter can be used to add, remove, or rebalance color. For example, take 2 pixels in an image. If the first is RGB 100 50 50 and the second is RGB 47 255 0, applying a colorization of -10 50 25 will result in:
  • Pixel 1 (100 50 50) -> 100+(-10) 50+50 50+25 -> RGB 90 100 75
  • Pixel 2 ( 47 255 0) -> 47+(-10) 255+50 0+25 -> RGB 37 255 25

Implementation
First off, what we need to do is load an image to colorize

import Graphics.GD
import System.Environment 

main = do  
      (inpath:outpath:ir:ig:ib:others) <- getArgs  
      let  
           r = read ir :: Int  
           g = read ig :: Int  
           b = read ib :: Int  
      img <- loadPngFile inpath  
      alphaBlending False img  
      saveAlpha True img  
      colorize img (r,g,b)  
      savePngFile outpath img
  

Here we read from the command line arguments, and convert the r, g, and b (represented by the inputs ir, ig, ib) into Ints. If you are familiar with the GD Haskell library, you will notice that in the call to 'colorize', we pass the values as a triple, rather than as a GD Color. This is because colorize can accept values from -255 to +255. Values below 0 are not valid RGB color values, so we can't represent a colorization of -255 0 0 as a Color

Before going further, since I knew I would need to do addition/subtraction of color values, I wrote a quick "clamp" function for myself, so that I could ensure that any color values I created would result in valid RGB values between 0 and 255 (a quick clamping function isn't a bad idea to have when you are doing math, anyway!):

-- generic clamp function
-- for use with rgb math: `clamp 0 255 calcdvalue`
clamp minm maxm num  
      | num < minm = minm  
      | num > maxm = maxm  
      | otherwise = num 

-- an alternate, rgb specific clamp 'point free':
-- call with: `clampRGB calcdvalue`
clampRGB = max 0 $ min 255


Here's my colorize function. Since the function needs to iterate over each pixel in the image, I wrote a wrapper called colorize and put all the real functionality in colorize'. This helps in a few ways:
  • We don't need to call the imageSize function to grab the image's dimensions on EVERY pixel iteration. The image size won't change, so we only need to call imageSize inside colorize, and pass the height/width to colorize'
  • It's necessary to pass in the previous X and Y that we checked on each iteration so that we know what pixel to colorize next. It's not very friendly to make users enter in initializer parameters when they don't care. Therefore, colorize takes care of passing in the intial 0,0 X and Y.

colorize:: Image -> (Int, Int, Int) -> IO ()  
colorize img color = do  
      (width,height <- imageSize img  
      colorize' img color (0,0) (width,height)  

colorize' :: Image -> (Int, Int, Int) -> (Int, Int) -> (Int, Int) -> IO ()  
colorize' img (sr,sg,sb) (x,y) (w,h) = do  
      currColor <- getPixel (x,y) img  
      let  
           (r,g,b,a) = toRGBA currColor  
           doColorization  
                | x > w = colorize' img (sr,sg,sb) (0,y+1) (w,h)  
                | y > h = return ()  
                | a == 127 = colorize' img (sr,sg,sb) (x+1,y) (w,h)  
                | otherwise = do  
                     let  
                          nr = clamp 0 255 (r+sr)  
                          ng = clamp 0 255 (g+sg)  
                          nb = clamp 0 255 (b+sb)  
                          newcolor = rgba nr ng nb a  
                     setPixel (x,y) newcolor img  
                     colorize' img (sr,sg,sb) (x+1,y) (w,h)  
      doColorization 


Here's the rundown of how it all works:
  • colorize is called, with it's input being an Image and a triple representing how we want to colorize each pixel
  • colorize grabs the Image's width and height, then calls colorize', passing in the Image, the colorization triple, (0,0)  - the starting pixel location for our recursive colorize' function, and the width and height we grabbed
  • colorize' tries to get the current color at the supplied pixel.
  • colorize' defines an internal function, doColorization... in doColorization, we cover several conditions before any colorization can be done:
    • if the X value we're looking at is greater than the width of the image, don't do anything on this iteration, and call colorize' again, this time resetting X to 0, and Y to Y+1 (we're looking at the next row of pixels, now)
    • if the Y value we're looking at is greater than the height of the image, that means we've finished iterating over all the image's rows, so we should just return ().
    • if the alpha value of the current pixel's current color is 127 ( fully transparent), then we should just move on to the next X pixel; colorizing a fully transparent pixel makes no sense
    • Finally! we're ready to colorize! Actually doing the colorization is so simple that you will probably wonder why it's taken so much text to explain! For the R, G and B components of the current color  at the current pixel, add to their value the R, G and B values (respectively) of the color we wish to colorize the image to. Each of the R, G and B are clamped between 0 and 255. Next, we set the current pixel's color to the new color we calculated, and the move on to the next pixel
Now: to test it! I'm going to use the haskell logo, which I saved as haskell.png, and color it a light blue:

ghc -O2 colorization.hs

./colorization haskell.png coloredhaskell.png 15 85 127


Colorized
Original

Wrap-up
So, that's my simple colorize filter. I know it's probably not the most elegant implementation, but it works and it runs fast (which ticks the boxes for what I need). I'm thinking of putting together more Haskell image filters in the near future; at least implementing the filters that PHP supports to help out anyone else who, like me, is in the process of moving from PHP to Haskell. Maybe more

No comments:

Post a Comment