title: Automatically cropping an image using Python
body: <p>I want to automatically crop an image using <code>OpenCV</code> into many images, the number of output images is variable. I started by replacing the white background by a transparent background.</p>
  
  <p>The input image: 
  <a href="https://i.stack.imgur.com/pkcJS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pkcJS.png" alt="enter image description here"></a></p>
  
  <p>I replace the white background by a transparent background using this script: </p>
  
  <pre class="lang-py prettyprint-override"><code>from PIL import Image
  
  img = Image.open('./images/SPORTS/546.png')
  img = img.convert("RGBA")
  datas = img.getdata()
  
  newData = []
  for item in datas:
      if item[0] == 253 and item[1] == 252 and item[2] == 252:
          newData.append((255, 255, 255, 0))
      else:
          newData.append(item)
  
  img.putdata(newData)
  img.show()
  img.save("split_image_example.png", "PNG")
  </code></pre>
  
  <p>So in this example I want to get 4 separated images.</p>
  
  <p><a href="https://i.stack.imgur.com/35vkZm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/35vkZm.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/wBnZRm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wBnZRm.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/8In3gm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8In3gm.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/2gfR6m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2gfR6m.png" alt="enter image description here"></a></p>