Implementing Gaussian Blur - How to calculate convolution matrix (kernel)

后端 未结 7 2046
予麋鹿
予麋鹿 2020-12-22 21:14

My question is very close to this question: How do I gaussian blur an image without using any in-built gaussian functions?

The answer to this question is very good,

7条回答
  •  醉话见心
    2020-12-22 21:53

    Gaussian blur in python using PIL image library. For more info read this: http://blog.ivank.net/fastest-gaussian-blur.html

    from PIL import Image
    import math
    
    # img = Image.open('input.jpg').convert('L')
    # r = radiuss
    def gauss_blur(img, r):
        imgData = list(img.getdata())
    
        bluredImg = Image.new(img.mode, img.size)
        bluredImgData = list(bluredImg.getdata())
    
        rs = int(math.ceil(r * 2.57))
    
        for i in range(0, img.height):
            for j in range(0, img.width):
                val = 0
                wsum = 0
                for iy in range(i - rs, i + rs + 1):
                    for ix in range(j - rs, j + rs + 1):
                        x = min(img.width - 1, max(0, ix))
                        y = min(img.height - 1, max(0, iy))
                        dsq = (ix - j) * (ix - j) + (iy - i) * (iy - i)
                        weight = math.exp(-dsq / (2 * r * r)) / (math.pi * 2 * r * r)
                        val += imgData[y * img.width + x] * weight
                        wsum += weight 
                bluredImgData[i * img.width + j] = round(val / wsum)
    
        bluredImg.putdata(bluredImgData)
        return bluredImg
    

提交回复
热议问题