title: Implementing a bilateral filter
body: <p>I am trying to implement a bilateral filter from the paper <a href="https://people.csail.mit.edu/fredo/PUBLI/Siggraph2002/DurandBilateral.pdf" rel="nofollow noreferrer">Fast Bilateral Filteringfor the Display of High-Dynamic-Range Images</a>. The equation (from the paper) that implements the bilateral filter is given as :</p>
  
  <p><a href="https://i.stack.imgur.com/Ox5oO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ox5oO.png" alt="enter image description here"></a></p>
  
  <p>According to what I understood,</p>
  
  <ul>
  <li>f is a Gaussian filter</li>
  <li>g is a Gaussian filter</li>
  <li>p is a pixel in a given image window</li>
  <li>s is the current pixel</li>
  <li>Ip is the intensity at the current pixel</li>
  </ul>
  
  <p>With this, I wrote the code to implement these equations, given as :</p>
  
  <pre><code>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 &gt; 0 and index + c &lt; 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 &gt; 0 and index + c &lt; 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)
  </code></pre>
  
  <p>But as I run this code I get an error saying: </p>
  
  <pre><code>    Traceback (most recent call last):
  File "bft.py", line 33, in &lt;module&gt;
      (f * (p-s)) * (g * (i_p * i_s))
  ValueError: operands could not be broadcast together with shapes (5,3) (5,239) 
  </code></pre>
  
  <p>Did I incorrectly implement the equations? What am I missing?</p>