title: Remove image background and extract the object in image
body: <p>I know that there are many threads here about this issue, but I'm not able to solve my problem with those answers. I tried many times with different codes to remove the background of an image like this:
  <a href="https://i.stack.imgur.com/773A4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/773A4.jpg" alt="With Background"></a></p>
  
  <p>to this:</p>
  
  <p><a href="https://i.stack.imgur.com/7KbJh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7KbJh.png" alt="Without Background"></a></p>
  
  <p>with the following code:</p>
  
  <pre><code>img2 = Image.open("foo.jpg")
  c_red, c_green, c_blue = cv2.split(img2)
  img2 = cv2.merge((c_red, c_green, c_blue, mask.astype('float32') / 255.0))
  img.paste(img2,(0,0))
  </code></pre>
  
  <p>or with this code:</p>
  
  <pre><code>img2 = Image.open("foo.jpg")
  img2 = img2.convert("RGBA")
  datas = img2.getdata()
  
  newData = []
  for item in datas:
      if item[0] == 255 and item[1] == 255 and item[2] == 255:
          newData.append((255, 255, 255, 0))
      else:
          newData.append(item)
  img2.putdata(newData)
  </code></pre>
  
  <p>or:</p>
  
  <pre><code>threshold=100
  dist=5
  img2 = Image.open("foo.jpg")
  img2 = img2.convert("RGBA")
  
  arr=np.array(np.asarray(img2))
  r,g,b,a=np.rollaxis(arr,axis=-1)    
  mask=((r&gt;threshold)
        &amp; (g&gt;threshold)
        &amp; (b&gt;threshold)
        &amp; (np.abs(r-g)&lt;dist)
        &amp; (np.abs(r-b)&lt;dist)
        &amp; (np.abs(g-b)&lt;dist)
        )
  arr[mask,3]=0
  img2=Image.fromarray(arr,mode='RGBA')
  </code></pre>
  
  <p>But none of them does not work. The thing I want to do is remove the background of any color (transparent) and change the borders of an image to its object's border as I showed above. Any help is appreciated.</p>