title: Remove undesired connected pixels from an image with Python
body: <p>I'm a beginner in image processing with Python so I need help.
  I'm trying to remove areas of connected pixels from my pictures with the code posted below. Actually, it works but not well. 
  What I desire is the removing of areas of pixels, such as those marked in red in the pictures reported below, from my images, so as to obtain a cleaned picture. 
  Would be also great to set a minimum and a maximum limit for the dimensions of the detected areas of connected pixels.
  <a href="https://i.stack.imgur.com/jnP7u.jpg" rel="nofollow noreferrer">Example of a picture with marked areas 1</a>
  <a href="https://i.stack.imgur.com/63JQF.jpg" rel="nofollow noreferrer">Example of a picture with marked areas 2</a></p>
  
  <p><a href="https://i.stack.imgur.com/pgiUC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pgiUC.jpg" alt="Original picture"></a></p>
  
  <p>This is my currently code:</p>
  
  <pre><code>### LOAD MODULES ###
  import numpy as np
  import imutils
  import cv2
  
  def is_contour_bad(c): # Decide what I want to find and its features
      peri=cv2.contourArea(c, True) # Find areas
      approx=cv2.approxPolyDP(c, 0.3*peri, True) # Set areas approximation
      return not len(approx)&gt;2 # Threshold to decide if add an area to the mask for its removing (if&gt;2 remove)
  
  
  ### DATA PROCESSING ###
  image=cv2.imread("025.jpg") # Load a picture
  gray=cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Convert to grayscale
  cv2.imshow("Original image", image) # Plot
  
  edged=cv2.Canny(gray, 50, 200, 3) # Edges of areas detection
  cnts=cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # Find contours: a curve joining all the continuous points (along the boundary), having same color or intensity
  cnts=imutils.grab_contours(cnts)
  
  mask=np.ones(image.shape[:2], dtype="uint8")*255 # Setup the mask with white background
  # Loop over the detected contours
  for c in cnts:
      # If the contour satisfies "is_contour_bad", draw it on the mask
      if is_contour_bad(c):
          cv2.drawContours(mask, [c], -1, 0, -1) # (source image, list of contours, with -1 all contours in [c] pass, 0 is the intensity, -1 the thickness)
  
  image_cleaned=cv2.bitwise_and(image, image, mask=mask) # Remove the contours from the original image
  cv2.imshow("Adopted mask", mask) # Plot
  cv2.imshow("Cleaned image", image_cleaned) # Plot
  cv2.imwrite("cleaned_025.jpg", image_cleaned) # Write in a file
  </code></pre>