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

No comments:

Post a Comment