Thursday, March 22, 2012

The great CNC project!

About two weeks ago, my good friend Jesse and I got it into our heads that we needed to start building guitars. This isn't a completely uninformed plan; I have built electric guitars before and Jesse has done some custom metalwork for a luthier before. Our plan involves some seriously interesting combinations of metal and woodwork... but more on that later ;)

Rather than sit around hoping that the plan would go somewhere, we decided to be proactive. A CNC is an excellent tool when working on guitars; you can get the rough shape cut, all the major routs done, cut the rough pockets for inlays, as well as the inlay itself. Of course, buying a CNC is not an easy thing (a CNC of any kind of reasonable size is multiple thousands of dollars - $10k+ is not uncommon for a 2'x3' industrial CNC). The obvious solution is for us to build our own CNC...obviously.

Building a CNC at home actually isn't as insane as you would think. Lots of people are doing it. And there are lots of resources. From all I've seen, you can build a quite excellent home CNC machine for well under $1000. We're still early in the process, so I will be posting some updates as we proceed in constructing our machine. So here's the rundown of what we've got so far...

Plans
Rather than making up our own construction or trying to follow some badly organized online plans, we opted to buy a set of plans for home CNC construction. We grabbed the 25"x25" plans from Solsylva, which also come with plans for a 13"x13" engraving CNC (you can use a small trim router or even Dremel, depending on what materials you want to cut) and plans for a 24"x48" CNC. The set of 3 plans runs for $35, and are excellent.






Electronics & Motors
We chose to plan only for a 3-axis machine; that's what the plans we grabbed were made for and a 4th axis doesn't seem very useful without a 5th axis too.

Instead of getting all of the electronics piece by piece and leaving their compatibility up to our own luck, we grabbed a 3-axis driver board kit from HobbyCNC, that includes the board, all electronics (aside from the actual computer you plug into and a transformer) and the stepper motors for each axis.

Man... these motors are just plain awesome. And heavy. 

The rest...
Hopefully, within the next few days, we'll have the structural materials. I'll be updating with more information when we start throwing things together.

The plan is to get this fully operational in the next week or two.

Saturday, January 21, 2012

Loop-like IO actions in Haskell

In the course of writing my imagefilters library for Haskell, I came across the need for loop-like control structures when it came to applying a transformation to every pixel in an image. Given that all of the actions relating to pixel modification are IO monad actions, things are mildly more complicated than if I were just dealing with numbers inside a pure Haskell function.

List Comprehensions?
My first thought was something with list comprehensions... (Note; some of this is pseudo-code-y... those parts are italicized)

  pixelTransform img transformFunction = do  
      (width,height) <- imageSize img  
      [ do   
                get pixel x y
                transformFunction pixel   
                set pixel to new value   
           | x <- [ 0..(imageWidth-1) ], y <- [ 0..(imageHeight-1) ]]   

Makes sense, right? For every combination of x and y, do the series of IO actions required to transform it. Turns out Haskell isn't a fan of IO inside of list comprehensions; you might get it to compile okay (if you spend time wrapping "return" calls around things), but nothing will happen.

'do' Style?
After some research, I found that Haskell supports a monadic form of list comprehension (see the update at the bottom) using do-notation

 do  
      x <- [ 0..10 ]  
      y <- [ 0..10 ]  
      return (x+y)  

Cool Right? that will give us back a list of the sums of all combinations of x and y. If that works, then I should be able to do this, right?

 pixelTransform img transformFunction = do  
      (width,height) <- imageSize img  
      x <- [ 0..(width-1) ]   
      y <- [ 0..(height-1) ]   
      get pixel x y 
      transformFunction pixel   
      set pixel to new value   
      return ()  

Well, no. This doesn't fly either. And when we think about it, it makes sense. 'do' notation is syntactic sugar for constructing monadic actions together with the >>= (bind) operator. The above is the same as doing:

 pixelTransform img transformFunction = return () >>=   
      imageSize img >>=  
      (\(width,height) -> [0..(width-1)] >>=    
      \x -> [0..(height-1) >>=    
      \y -> get pixel x y >>=    
      \pixel -> transformFunction pixel >>=   
      \new value -> set pixel to new value     

That IS kind of ugly looking, but it doesn't show what the problem *really* is until we look at the type signature for >>=

 ghci>:t ( >>= )  
 ( >>= ) :: Monad m => m a -> (a -> m b) -> m b 

Ah. So >>= takes a monad with some type a, a function which takes regular type a and returns a monad with some type b, and then applies that function to the monad with type a, which ends up returning a monad with type b.

Remember: Just because the input is m a, and the output is m b, it does not mean that they are different monads; the m is still there in both of them... it is the same monadic type, but it *may* contain a different type inside of it (if you think of the box analogy - a monad is a box which contains other values). 

If you think about what our previous example is doing, you'll realize that the big issue is that we're trying to use completely different monads together. Applying an IO monad's result to a List monad doesn't make any sense (and vice versa)! So, in order to use multiple Monadic actions together within a do, they either need to be the same type, or they need to be wrapped in calls to return to put them into the right monadic context, but that gets sort of messy. So, what's the easiest way to do what I'm trying to do?

mapM_ saves the day
mapM_ is a function that lives inside the Control.Monad. It's kind of like the regular map that we all know and love, but it's meant for use with monads. About the name of the function - the 'M' stands for the fact that it takes a regular old type value and returns a monad, and the '_' just means that instead of returning m something, it is going to return m (). In our case, that means that the return type of mapM_ is going to be IO ().

Using map makes sense; we know the dimensions of the image (by grabbing the image size), so we can build a list of all combinations of x and y values between 0 and their respective sizes, and then map our transform function over each pixel

So now, the per-pixel transform function becomes this:

 import Control.Monad (mapM_)  

 pixelTransform img transformFunction = do   
      (width,height) <- imageSize img   
      mapM_ (\(x,y) -> do   
                get pixel x y   
                transformFunction pixel   
                set pixel to new value   
           )    
           [ (x,y) | x <- [0..(width-1)], y <- [0..(height-1)] ]

Easy enough; the list comprehension at the end builds a list of tuples representing every possible x,y coordinate in the image and that is the list that we mapM_ over. The function we pass to mapM_ pattern matches the tuple, and then performs our pixel transformation there, then moves on.

As you can see, we used a list comprehension to build the list of x,y pairs. If you are a fan of Applicative Functors (like I am!), you can use the <$> and <*> operators to build the same list to pass to mapM_
 
 import Control.Monad (mapM_)  
 import Control.Applicative  

 pixelTransform img transformFunction = do   
      (width,height) <- imageSize img   
      mapM_ (\(x,y) -> do   
                get pixel x y   
                transformFunction pixel   
                set pixel to new value   
           )    
           $ (,) <$> [0..(width-1)] <*> [0..(height-1)]   

Wrap up
So far, mapM_ has been the best solution that I've found for looping over multidimensional list values with IO () actions, but if anybody else has found other/better/clearer ways of achieving the same results, I'd love to hear them

Update: I've found out that the reason why list comprehensions don't work is the exact same reason why do notation doesn't work; list comprehensions are syntactic sugar for using >>=, so it has the same requirements as a do block, in terms of Monad consistency

Sunday, January 15, 2012

imagefilters (Haskell image filters for GD) v0.1 released

I've just published the first release of my imagefilters package on Hackage. Hopefully some people will find it useful, and I can get some good feedback through the release.

Features
  •  10 image filters
    • Brightness
    • Colorize
    • Contrast
    • Edge Detect
    • Emboss
    • Gaussian Blur
    • Grayscale
    • Invert Color
    • Mean Removal
    • Smoothing
  • Filter utility functions (for custom filters)
    • pixelTransform - for applying per-pixel color adjustments 
    • convolute - for applying convolution matrices. This is used for many of the more "complicated" filters, like Emboss and Gaussian blur
What's missing
  • No pixelate filter, yet
  • No selective blur yet either
  • Filters are only compatible with the GD plugin; I would like to include filters that are compatible with other common imaging plugins
  • The code probably needs some better error handling and also some optimization/cleanup

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

Monday, July 12, 2010

SVN pre-revprop-change hook script, to allow log edits

SVN hook scripts are little scripts which SVN attempts to call automatically during various operations. The svn pre-revprop-change hook script is one that is called when you try to modify a property of a revision. The most common use of this script is to allow the editing of svn log comments.

Hook script templates should already exist, in the /hooks directory inside your repository director. For me, I have several repos in /var/svn. Say I want to set up comment editing for a particular repo named 'svnrepo1'. My hook templates would be in /var/svn/svnrepo1/hooks.

To activate one of the template hooks, simply rename it to match whatever hook it should be with. For example, my pre-revprop-change template was named 'pre-revprop-change.tmpl' - to activate it, I copied (better idea than just moving it) it to 'pre-revprop-change'. Here's the code inside the pre-revprop-change hook:


# 5 ordered arguments are sent to pre-revprop-change:
# [1] path to repository
# [2] the revision being modified
# [3] username of the person editing the revision
# [4] the property being modified
# [5] the action; 'A'dded, 'M'odified, 'D'eleted


# assigning the arguments to named variables
REPO="$1"
REV="$2"
USER="$3"
PROPNAME="$4"
ACTION="$5"


# we only want to allow 'M'odifiying of svn:log.
# No adding or deleting,
# and no changing of other properties
if[ "$ACTION" = "M" -a "$PROPNAME" = "svn:log"]; then exit 0; fi

exit 1



That's all. All the pre-revprop-change hook needs to do, is make sure people aren't doing anything they shouldn't do, and then exit 0 if they're being good little kids, and exit 1 if they're breaking the rules. This script can also be easily modified to only allow the original comment's author to change the comment. To do this, just change the "if" statement to look like this:

if [ "$ACTION = "M" -a "$PROPNAME" = "svn:log" -a `svnlook author /path/to/your/repo -r $REV` = "$USER" ]; then exit 0; fi


This uses the svnlook utility to check if the username associated with the revision ($REV) matches the person editing it ($USER)