【发布时间】:2020-03-12 08:48:59
【问题描述】:
我正在尝试从Fast Bilateral Filteringfor the Display of High-Dynamic-Range Images 论文中实现双边过滤器。实现双边滤波器的方程(来自论文)如下:
据我了解,
- f 是一个高斯滤波器
- g 是一个高斯滤波器
- p 是给定图像窗口中的一个像素
- s 是当前像素
- Ip 是当前像素的强度
有了这个,我编写了实现这些方程式的代码,如下所示:
import cv2
import numpy as np
img = cv2.imread("fish.png")
# image of width 239 and height 200
bl_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
i = cv2.magnitude(
cv2.Sobel(bl_img, cv2.CV_64F, 1, 0, ksize=3),
cv2.Sobel(bl_img, cv2.CV_64F, 0, 1, ksize=3)
)
f = cv2.getGaussianKernel(5, 0.1, cv2.CV_64F)
g = cv2.getGaussianKernel(5, 0.1, cv2.CV_64F)
rows, cols, _ = img.shape
filtered = np.zeros(img.shape, dtype=img.dtype)
for r in range(rows):
for c in range(cols):
ks = []
for index in [-2,-1,1,2]:
if index + c > 0 and index + c < cols-1:
p = img[r][index + c]
s = img[r][c]
i_p = i[index+c]
i_s = i[c]
ks.append(
(f * (p-s)) * (g * (i_p * i_s)) # EQUATION 7
)
ks = np.sum(np.array(ks))
js = []
for index in [-2, -1, 1, 2]:
if index + c > 0 and index + c < cols -1:
p = img[r][index + c]
s = img[r][c]
i_p = i[index+c]
i_s = i[c]
js.append((f * (p-s)) * (g * (i_p * i_s)) * i_p) # EQUATION 6
js = np.sum(np.asarray(js))
js = js / ks
filtered[r][c] = js
cv2.imwrite("f.png", filtered)
但是当我运行这段代码时,我收到一条错误消息:
Traceback (most recent call last):
File "bft.py", line 33, in <module>
(f * (p-s)) * (g * (i_p * i_s))
ValueError: operands could not be broadcast together with shapes (5,3) (5,239)
我是否错误地实现了方程式?我错过了什么?
【问题讨论】:
-
您的矩阵形状不兼容,您不能将一个尺寸为 5,3 的矩阵与另一个尺寸为 5,239 的矩阵相乘
-
@prhmma 你知道对上述等式进行编码的正确方法吗?
-
更改这两行并检查它是否工作
ks.append(np.matmul((f * (p-s)).T, (g * (i_p - i_s))) # EQUATION 7和js.append(np.matmul((f * (p-s)).T, (g * (i_p * i_s)) * i_p)) # EQUATION 6 -
@prhmma 不确定这是否是矩阵乘法
-
您需要索引高斯内核(或者更好的是使用插值)。方程中的 f(p-s) 表示在 p-s 处评估高斯。
标签: python algorithm opencv computer-vision dynamic-programming