NHDaly
NHDaly

Reputation: 8076

How can I blur an image in Julia?

I have an image I've loaded as an array of pixels (with Image.jl). How can I blur that image using a simple function that just averages the pixels with some number of the surrounding pixels?

Upvotes: 2

Views: 473

Answers (1)

NHDaly
NHDaly

Reputation: 8076

Here is a simple blurred(img, n) function that blurs every pixel in an image with the surrounding n pixels.

The only tricky bit here is deciding what to do at the edges. In this case, I've mirrored the edges (via getpixel), which I think gives a decent blur.

This algorithm is very naive, though, so it performs badly when n gets much larger than around 50...

# --------------------------
# using Images, FileIO
#
# include("blur.jl")
#
# img = FileIO.load("img.png")
#
# FileIO.save("blurred.png", blurred(img, 20))
# --------------------------

using Statistics: mean

function blurred(image, n)
    reshape([
        blurred_px(image, x,y, n)
        for x in 1:size(image)[1], y in 1:size(image)[2]
    ], size(image))
end

function blurred_px(image, x,y, n)
    mean(
        getpixel(image, i, j)
        for i in x-n:x+n, j in y-n:y+n
    )
end

function getpixel(image, x,y)
    w,h = size(image)
    # mirror over top/left
    x,y = abs(x-1)+1, abs(y-1)+1
    # mirror over the bottom/right
    if x > w
        x = w+ (w - x)
    end
    if y > h
        y = h+(h - y)
    end
    return image[x, y]
end

blurred

For example: enter image description here enter image description here

Upvotes: 2

Related Questions