title: How to remove noise of image?
body: <p>Currently I am trying to get rid of all background noises from my images. </p>
  
  <p>I'm pretty sure I have to use some kind of <strong>Dilation</strong> or <strong>Erosion</strong> algorithm but I also like to achieve coding the <strong>filter routine</strong> in Swift.</p>
  
  <p>This is my unfiltered noisy image:</p>
  
  <p><img src="https://i.stack.imgur.com/AQEOQ.jpg" alt="unfiltered Image"></p>
  
  <p>And this could be what It should look like <strong>after applying the filter</strong>:</p>
  
  <p><img src="https://i.stack.imgur.com/MDyOo.jpg" alt="filtered Image"></p>
  
  <p><strong>Note:</strong> Using openCV the code should look maybe like this <em>(but like I'd mentioned-  I'd like to use Swift instead)</em>:</p>
  
  <pre><code>img = cv2.imread("img.png")
  bggray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  labelnum, labelimg, contours, GoCs = cv2.connectedComponentsWithStats(bggray)
  for label in xrange(1, labelnum):
      x,y,w,h,size = contours[label]
      if size &lt;= 50:
           img[y:y+h, x:x+w] = 0
  cv2.imwrite("img.png", img)
  </code></pre>
  
  <p><strong>Note:</strong> This is the Swift code I got so far but it is obviously not working this way:</p>
  
  <pre><code>class CleanupFilter: CIFilter {
      var inputImage : CIImage?
      var threshold1: Float = 0.5
      var threshold2: Float = 0.7
      var thresholdKernel =  CIColorKernel(source:
          "kernel vec4 thresholdKernel(sampler image, float threshold1, float threshold2) {" +
              "vec4 pixel = sample(image, samplerCoord(image));" +
              "const vec3 rgbToIntensity = vec3(0.114, 0.587, 0.299);" +
              "float intensity = dot(pixel.rgb, rgbToIntensity);" +
              "if (intensity &lt; threshold1) {return vec4(0, 0, 0, 0)}" +
              "if (intensity &lt; threshold1 &amp;&amp; intensity &gt; threshold2) {return vec4(1, 1, 1, 1)}" +
              "else {return vec4(0, 0, 0, 0)}" + "}")
      override var outputImage: CIImage! {
          guard let inputImage = inputImage,
              let thresholdKernel = thresholdKernel else {
                  return nil
          }
          let extent = inputImage.extent
          let arguments : [Any] = [inputImage, threshold1, threshold2]
          return thresholdKernel.apply(extent: extent, arguments: arguments)
      }
  }
  </code></pre>
  
  <p>Any help how to edit <strong>thresholdKernel</strong> to achieve a working filter routine would be very appreciated.</p>