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:
to this:
with the following 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))
or with this 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)
or:
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>threshold)
& (g>threshold)
& (b>threshold)
& (np.abs(r-g)<dist)
& (np.abs(r-b)<dist)
& (np.abs(g-b)<dist)
)
arr[mask,3]=0
img2=Image.fromarray(arr,mode='RGBA')
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.