首页 > 解决方案 > 如何在 Julia 中模糊图像?

问题描述

我有一个已加载为像素数组的图像(使用 Image.jl)。如何使用一个简单的函数来模糊该图像,该函数仅将像素与一些周围像素进行平均?

标签: imagejuliablur

解决方案


这是一个简单的blurred(img, n)函数,可以用周围的像素模糊图像中的每个n像素。

这里唯一棘手的一点是决定在边缘做什么。在这种情况下,我已经镜像了边缘(通过getpixel),我认为这会产生不错的模糊效果。

但是,该算法非常幼稚,因此当 n 远大于 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

例如: 在此处输入图像描述 在此处输入图像描述


推荐阅读