我写了一些高斯滤波器代码,但它看起来并不像OpenCV的GaussianBlur具有相同的参数:
#!/usr/bin/env python3
import numpy as np
import math
import cv2
def get_raw_data(image_dims, rescale_factor=5):
img = np.random.rand(
image_dims[0] // rescale_factor, image_dims[1] // rescale_factor, 1)
return cv2.resize(img, (0, 0),
fx=rescale_factor, fy=rescale_factor,
interpolation=cv2.INTER_NEAREST)
def psf(diameter):
radius = diameter / 2
kernel = np.zeros((diameter, diameter, 1), dtype="float")
for i in range(-diameter // 2, diameter // 2 + 1):
for j in range(-diameter // 2, diameter // 2 + 1):
new_val = normal_pdf(i, 0, radius) * \
normal_pdf(j, 0, radius)
kernel[i + diameter // 2, j + diameter // 2] = new_val
return kernel
def normal_pdf(x, m, s):
inv_sqrt_2pi = 0.3989422804014327
a = (x - m) / s
return inv_sqrt_2pi / s * math.exp(-0.5 * a * a)
def main():
print(psf(5))
raw_data = get_raw_data((50, 100))
blurred = cv2.filter2D(raw_data, -1, psf(5))
cv2.imshow("raw", cv2.resize(raw_data,
(1800, 900),
interpolation=cv2.INTER_NEAREST))
cv2.waitKey()
cv2.imshow("blurred", cv2.resize(blurred,
(1800, 900),
interpolation=cv2.INTER_NEAREST))
cv2.waitKey()
blurred = cv2.GaussianBlur(raw_data, (5, 5), 0, 0)
cv2.imshow("blurred", cv2.resize(blurred,
(1800, 900),
interpolation=cv2.INTER_NEAREST))
cv2.waitKey()
if __name__ == '__main__':
main()
在大多数情况下,看起来我的模糊图像比OpenCV生成的图像更暗。我怀疑我计算PSF的方式有问题,但我不确定我做错了什么。
编辑:用blurred = cv2.GaussianBlur(raw_data, (5, 5), 0, 0)
替换blurred = cv2.GaussianBlur(raw_data, (5, 5), 5, 5)
有帮助,虽然我的模糊仍然会产生比OpenCV更暗的值。