Building a contrast enhancement filter in Julia (ii)

This is what the filter we are building in Julia currently looks like:

function localStatENH(img, k, n)

    dx, dy = size(img)
    imgN = copy(img)
    w = div(n,2)
end

Next to be added is the pixel processing, built using a nested-loop. If the image to be filtered is dx=100, dy=100, and w=2 (n=5), then the value of i=3:98, and j=3:98. (This allows for a 2-pixel wide border to deal with edge effects, as discussed in the previous post).

for i=w+1:dx-w, j=w+1:dy-w

end

Within the loop, the neighbourhood surrounding a pixel is extracted – we call this a block. 

block = img[i-w:i+w, j-w:j+w]

This effectively extracts a slice of the 2D array. The pixel at location[3,3], therefore extracts the region img[3-2:3+2, 3-2:3+2] which is effectively img[1:5,1:5] – the block bounded by rows 1 to 5 and columns 1 to 5, containing 25 pixels.

The one statistic needed from this block is the mean, which can be calculated using the Julia function mean().

statB = mean(block)

Now the equation to perform the enhancement and calculate the new pixel can be formulated:

newP = statB + k * (img[i,j] - statB)

Here is what the function looks like now. All that needs to happen now is some tidying up.

function localStatENH(img, k, n)

    dx, dy = size(img)
    imgN = copy(img)
    w = div(n,2)

    for i=w+1:dx-w, j=w+1:dy-w
        block = img[i-w:i+w, j-w:j+w]
        statB = mean(block)
        newP = statB + k * (img[i,j] - statB)
    end
end

Firstly any values of newP below 0 or above 255 should be treated, and finally the value in newP assigned to the appropriate pixel in the enhanced image imgN (first it is truncated and converted to a UInt8, i.e. value between 0 and 255).

function localStatENH(img, k, n)

    dx, dy = size(img)
    imgN = copy(img)
    w = div(n,2)

    for i=w+1:dx-w, j=w+1:dy-w
        block = img[i-w:i+w, j-w:j+w]
        statB = mean(block)
        newP = statB + k * (img[i,j] - statB)
        if (newP < 0)
            newP = 0
        elseif (newP > 255)
            newP = 255
        end
        imgN[i,j] = trunc(UInt8,newP)
    end
    return imgN
end

Voilà! The code has been written. But how does it work? We’ll check that out in the next post.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s