title: Trim (noised) whitespaces in images using Python
body: <p>Say that I have an image as shown below: </p>
  
  <p><a href="https://i.stack.imgur.com/1cAQF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1cAQF.jpg" alt="enter image description here"></a></p>
  
  <p>As you can see, the image contains blank/white space (noised with small green dots) in addition to a big green square (the square is randomly put in the left-bottom corner).
  What I want to do is to crop the image/trim the white space to only get the big green square in the end.<br>
  Thanks to <strong>Stackoverflow</strong> community, I found a way to trim the white space (if it does not contain noise) <a href="https://stackoverflow.com/a/10616717/8128190">in this answer</a>; here is the code that I used:  </p>
  
  <pre><code>from PIL import Image, ImageChops
  
  def trim(im):
      bg = Image.new(im.mode, im.size, im.getpixel((0,0)))
      diff = ImageChops.difference(im, bg)
      diff = ImageChops.add(diff, diff, 2.0, -100)
      diff.show()
      bbox = diff.getbbox()
      if bbox:
          return im.crop(bbox)
  
  im = Image.open("noised.jpg")
  im = trim(im)
  im.save('output.png')
  </code></pre>
  
  <p>Since the blank/white space contains noise, the cropped image that I got looks like this : </p>
  
  <p><a href="https://i.stack.imgur.com/hNezd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hNezd.png" alt="enter image description here"></a></p>
  
  <p>So the script cropped the image when it met the first non white (noised) pixel.<br>
  My question is: <strong>Is there a way to <em>denoise</em> the white space without affecting the image (green square) or to directly trim the white space even if it is noised?</strong><br>
  Thank you for your help!</p>