title: Remove spurious small islands of noise in an image - Python OpenCV
body: <p>I am trying to get rid of background noise from some of my images. This is the unfiltered image.</p>
  
  <p><img src="https://i.stack.imgur.com/CiBlj.png" alt=""></p>
  
  <p>To filter, I used this code to generate a mask of what should remain in the image:</p>
  
  <pre><code> element = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2))
   mask = cv2.erode(mask, element, iterations = 1)
   mask = cv2.dilate(mask, element, iterations = 1)
   mask = cv2.erode(mask, element)
  </code></pre>
  
  <p>With this code and when I mask out the unwanted pixels from the original image, what I get is:
  <img src="https://i.stack.imgur.com/0WDlX.png" alt=""></p>
  
  <p>As you can see, all the tiny dots in the middle area are gone, but a lot of those coming from the denser area are also gone. To reduce the filtering, I tried changing the second parameter of <code>getStructuringElement()</code> to be (1,1) but doing this gives me the first image as if nothing has been filtered. </p>
  
  <p>Is there any way where I can apply some filter that is between these 2 extremes?</p>
  
  <p>In addition, can anyone explain to me what exactly does <code>getStructuringElement()</code> do? What is a "structuring element"? What does it do and how does its size (the second parameter) affect the level of filtering?</p>