如何使用OpenCV的指令“ GaussianBlur”来演示opencv GausssianBlurr中使用的高斯内核?

问题描述

  • 我想演示 openCV 中使用的高斯内核cv2.GaussianBlurr(img,kernel_size,sigma)出于解释目的。
  • 我知道如何演示应用模糊后得到的图像,而这不是我的目标。
  • 我的目标是针对任何使用的sigma和任何使用的内核大小自动演示内核!
  • 我已经看过代码(在下文中有提及),但我更喜欢使用与OpenCV中使用的指令相关的更多内容,而不是仅仅依赖于一般的数学方法
  • 期望的输出内核是这样的:

image

import cv2
import numpy as np

# Read Image
img_path = 'image.jpg'
img = cv2.imread(img_path)
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

# Gaussian Blurr
Kernel = np.ones((15,15))
sigma = 2

Blurred_Image = cv2.GaussianBlur(img,(Kernel.shape[0],Kernel.shape[1]),sigma)

高斯内核手册代码

def dnorm(x,mu,sd):
    return 1 / (np.sqrt(2 * np.pi) * sd) * np.e ** (-np.power((x - mu) / sd,2) / 2)

def gaussian_kernel(size,sigma=1,verbose=False):
 
    kernel_1D = np.linspace(-(size // 2),size // 2,size)
    for i in range(size):
        kernel_1D[i] = dnorm(kernel_1D[i],sigma)
    kernel_2D = np.outer(kernel_1D.T,kernel_1D.T)
 
    kernel_2D *= 1.0 / kernel_2D.max()
 
    if verbose:
        plt.imshow(kernel_2D,interpolation='none',cmap='gray')
        plt.title("Image")
        plt.show()
 
    return kernel_2D

解决方法

这是Python / OpenCV中的一种方法。

 - Read the input
 - Create a delta image (one white pixel in the center of a black background)
 - Blur the image
 - List item
 - Resize the image to enlarge it
 - Stretch the image to full dynamic range
 - Save the result

import cv2
import numpy as np
import skimage.exposure as exposure

# create delta image
dims = 30
dims2 = 30 // 2
delta = np.zeros((dims,dims,3),dtype=np.float32)
delta[dims2:dims2+1,dims2:dims2+1] = (255,255,255)

# blur image
blur = cv2.GaussianBlur(delta,(0,0),sigmaX=5,sigmaY=5)

# resize 16x
dims4x = dims * 16
resized = cv2.resize(blur,(dims4x,dims4x),interpolation = cv2.INTER_AREA)

# stretch to full dynamic range
result = exposure.rescale_intensity(resized,in_range='image',out_range=(0,255)).astype(np.uint8)

# save image
cv2.imwrite('delta.png',delta)
cv2.imwrite('gaussian_blur_view.png',result)

# show the images
cv2.imshow("delta",delta)
cv2.imshow("result",result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Delta图片:

enter image description here

结果:

enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...