Friday, December 30, 2011

Haskell Image Filters: Colorize, Grayscale, Brightness, Contrast, and Invert Color

As per my current mission (here), I've been putting some of my free time into developing Haskell GD image filter equivalents to PHP's variety of filters provided by the imagefilter function. The past few days saw a LOT of progress. I've gone from having one filter implemented, to having five, and clearing up the code a lot to make adding any per pixel color filter much simpler to add. So far I've implemented:
  • Brightness Adjust
  • Colorize 
  • Contrast Adjust
  • Convert to Grayscale
  • Invert Color

Pixel Transform
My choice in implementing these particular filters first was not arbitrary; they are all relatively simple, and they all share commonality - each of them can be expressed as a simple mathematical operation on the R G B and A elements of each individual pixel. By implementing a flexible iteration function, I can pass in each of these filters as a simple function that simply takes the RGBA values of the given pixel, and returns the new RGBA for that pixel. To achieve this, I implemented a function that I called pixelTransform.

 pixelTransform :: Image -> ( (Int,Int,Int,Int) -> (Int,Int,Int,Int) ) -> IO()  
 pixelTransform img fx = do  
      (width,height) <- imageSize img  
      pixelTransform' img (0,0) (width,height) fx 
 
 pixelTransform' :: Image -> Point -> Size -> ( (Int,Int,Int,Int) -> (Int,Int,Int,Int) ) -> IO()  
 pixelTransform' img (x,y) (w,h) fx = do  
      curr <- getPixel (x,y) img  
      let   
           (r,g,b,a) = toRGBA curr  
           xform  
                | x > w = pixelTransform' img (0,(y+1)) (w,h) fx  
                | y > h = return ()  
                | otherwise = do  
                     let  
                          (nr,ng,nb,na) = (fx) (r,g,b,a)                           
                          newcol = rgba nr ng nb a  
                     setPixel (x,y) newcol img  
                     pixelTransform' img ((x+1),y) (w,h) fx  
      xform 
 

Here's the rundown:
  • pixelTransform takes an Image, and a function
    • the function is the transform function. It takes a quadruple of Ints, and returns a quadruple of Ints. In our terms: it takes the current R G B and A of a pixel, and returns a new R G B and A for that pixel
  • pixelTransform is intentionally simple, because it exists mostly for convenience for the user. It only really executes two actions:
    • It grabs the image's size
    • It calls its helper function, pixelTransform', passing the image, the initial X,Y location to iterate from, the image size and the transform function
  •  pixelTransform' (note the ') does the work. If you read my prior post on colorizing filters, this is mostly looking familiar:
    • Grab the current pixel's info
    • Using an internal function, handle recursing over the pixels. If our current pixel is within the bounds, do the transformation:
      • Simply apply the transform function we passed in, and set the current pixel's RGBA to the returned RGBA.
Easy, right? Then lets check out some of the actual filter transform function implementations:

Colorize
L: Original; R: Colorized with (50,100,-20,0)
The Colorize filter takes as it's argument a quadruple representing the per-pixel R,G,B and A change you desire. Each of these values can be either positive or negative. R,G and B are bounded -255 to +255, and A is bounded -127 to +127 (-127 will convert all pixels to opaque, 0 will keep the current pixel's alpha, and +127 will convert all pixels to transparent). For example, a colorization of (50,100,-20,0) represents the following change for each pixel of the image:
  • 50 added to it's current R
  • 100 added to it's current G
  • 20 subtracted from it's current B
  • No change to it's alpha ( or you can think of it as 0 added to it's current)

 colorize img (ar,ag,ab,aa) = do  
      pixelTransform img (\(r,g,b,a) -> let  
                nr = clamp 0 255 (r+ar)  
                ng = clamp 0 255 (g+ag)  
                nb = clamp 0 255 (b+ab)  
                na = clamp 0 127 (a+aa)  
           in (nr,ng,nb,na)) 
 

You can see that the colorize filter calls pixelTransform, and passes the image that was passed to it, along with a lambda function that performs the transformation (note: you'll notice I'm using a clamp function, I described it's implementation in my original colorize filter post) by adding the passed R, G, B and A values

Brightness
L: Brightness +85; C: Original; R: Brightness -85
Brightness is a really really simple filter to implement. It takes as it's argument an Int bounded -255 to +255. This represents the amount of brightness you want to add or subtract (-255 is full black, 0 is no change in brightness, and +255 is full white)

 brightness img brightVal = do  
      colorize img (brightVal,brightVal,brightVal,0) 
 
Look at that! We can just reuse the colorize filter, and pass in the same transformation for R, G and B. That's because brightness is a uniform adjustment across all colors.

Contrast
L: Contrast +65 (low contrast); C: Original; R: Contrast -65 (high contrast)
Being that contrast is somewhat less easy to conceptualize (being that I'm no color theoretician or even really very experienced with low level image processing), I opted to double check with what PHP does to implement a contrast adjustment:
  • Contrast takes one parameter - an Int bounded -100 to +100 (-100 is max contrast, 0 no change, +100 minimum contrast)
  • Contrast multiplier = ((100.0 - contrastArg)/100.0) ^ 2
  • Normalize RGBA (convert from 0-255 scale to 0.0-1.0 scale)
  • Each of the normalized RGBA components is transformed as such (using R as the example):
    • R = R - 0.5
    • R = R * Contrast multiplier
    • R = R + 0.5
    • denormalize R
Since normalizing is something I know will be useful when dealing with RGB a lot, I put together a quick normalizeRGB function

 normalizeRGB :: (Int,Int,Int) -> (Double,Double,Double)  
 normalizeRGB (r,g,b) = ((fromIntegral r)/255
                         ,(fromIntegral g)/255
                         ,(fromIntegral b)/255) 
 

 contrast img contVal = do  
      pixelTransform img (\(r,g,b,a) -> let  
                contr = (**2) $ (100.0 - (fromIntegral contVal) )/100.0  
                (ur,ug,ub) = normalizeRGB (r,g,b)  
                nr = clamp 0 255 $ (*) 255 . (+) 0.5 . (*) contr $ ur-0.5  
                ng = clamp 0 255 $ (*) 255 . (+) 0.5 . (*) contr $ ug-0.5  
                nb = clamp 0 255 $ (*) 255 . (+) 0.5 . (*) contr $ ub-0.5  
           in (truncate nr, truncate ng, truncate nb, a))  
 

Invert Color
L: Original; R: Inverted Color
Inverting Color is *way* extremely easy. For each component of RGB, return the absolute value of 255 - the component

 negative img = do  
      pixelTransform img (\(r,g,b,a) -> let  
                nr = abs 255-r  
                ng = abs 255-g  
                nb = abs 255-b  
           in (nr,ng,nb,a))
  

Grayscale
L: Original; R: Grayscale
Converting to Grayscale is a little bit weird. I checked out PHP's implementation, and it turns out there are some specific formulas for what to do with the current colors:
  • grayValue = 0.299*R + 0.587*G + 0.114*B
  • Set R,G and B to to grayValue

 grayscale img = do  
      pixelTransform img (\(r,g,b,a) -> let  
                newcol = truncate $ 0.299*(fromIntegral r) 
                                  + 0.587*(fromIntegral g) 
                                  + 0.114*(fromIntegral b)  
           in (newcol, newcol, newcol, a))  


Conclusions
Well, now I've cleared out the easy filters... I guess that means I'll need to take a look at how to do the more complicated stuff: Edge Detect, Emboss, Gaussian Blur, Selective Blur, Mean Removal, Smoothing, and Pixelate. Sometime in the near future, I'll probably put up a github page for my code. Once I'm closer to what I feel is an acceptable level of development (I've gone through some cleanup/organization and have actually done exceptions / proper argument handling), I'll add it to Hackage

Monday, December 26, 2011

Fractional Modulo Operation in Haskell

Today I ran into a situation where I wanted to use the mod function on some numbers. Numbers that had decimal points. Haskell had things to say about it... something along the lines of:


 ghci>6 `mod` 2.2
 Ambiguous type variable `a0' in the constraints:  
    (Num a0) arising from the literal `6' at <interactive>:1:1  
    (Integral a0) arising from a use of `mod' at <interactive>:1:3-7  
    (Fractional a0) arising from the literal `2.2'  
            at <interactive>:1:9-11  
   Probable fix: add a type signature that fixes these type variable(s)  
   In the first argument of `mod', namely `6'  
   In the expression: 6 `mod` 2.2  
   In an equation for `it': it = 6 `mod` 2.2  


Well, that's problematic. I shouldn't be *too* surprised... C++ and PHP apparently don't support doing fractional modulo either. But I want it to work in Haskell, so, I'm going to make it work. This is also a nice introduction to defining custom infix operators!

Modulo Concepts
As it turns out, there's more than one way that modulo can be defined.  Basically, the modulus is the remainder of the dividend divided by the divisor. In people terms, it means "what is left over when you try to divide X (dividend) by Y (divisor)". The difference between a modulo operation and remainder is in the definition of what happens when you have a negative dividend or divisor. And that is also where you come up with different flavors of modulo operation. What happens depends entirely on the programming language. Some languages say that the modulus always has the same sign as the dividend. Others say it always has the same sign as the divisor.

Implementation
Since we're implementing our custom modulo operation in Haskell, it's probably best to stick with what Haskell does with negative divisors/dividends in regular Integral modulo operation. Lets see what Haskell does with various combinations of argument sign:


 ghci>6 `mod` 5
  1
 ghci>6 `mod` (-5)
  -4
 ghci>(-6) `mod` (-5)
  -1
 ghci>(-6) `mod` 5
  4
  

So now we've got our standard. It turns out, Haskell uses floored division to do perform modulo operations. Floored division works like this :

quotient = floor (dividend/divisor)
remainder = dividend - divisor*quotient


When we expand that, we get a simple equation to use for our custom modulo:

remainder = dividend - divisor * ( floor (dividend/divisor) )

In Haskell:


 (%) :: (RealFrac a) => a -> a -> a  
 dividend % 0 = error "Division by Zero!"   
 dividend % divisor = dividend - divisor * (fromIntegral $ floor (dividend/divisor))  


There are a few things to note about this code:
  • In the % operator's type definition, the % is enclosed in parentheses. This is necessary for the compiler to make sense of a random symbol (or symbols) at the beginning of a line.
  • The operator's actual implementation looks weird... we're placing arguments BEFORE the function name ?! Many new Haskellers (including me, until I started researching this) don't know that you can define functions implicitly as infix functions. If you wanted to use a named function instead of a symbol/operator, you can define it as infix by putting it inside backticks (`):
    • x `myInfixFunc` y = do something or other
So lets do a sanity check and make sure we get good results:

 ghci>6 % 5  
  1.0  
 ghci>6 % (-5)  
  -4.0  
 ghci>(-6) % (-5)  
  -1.0  
 ghci>(-6) % 5  
  4.0
  

Well that looks good! Now lets try it on some actual fractional values:


 ghci>6 % 2.2  
  1.5999999999999996
  

If you want to make sure that this is right, you can try Googling "6 % 2.2". Because of rounding differences, you'll get "1.6", rather than "1.5(lots of 9's)". Awesome! We just made Haskell perform a modulo operation on fractional numbers!

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