Closed buithehien1991 closed 9 months ago
This is a very simple image, so you do not need a complicated algorithm to remove the background. The code below simply uses the inverted red color channel of the image as the alpha channel.
Note that your image was a JPG file which has been converted to PNG at some point, so it contains compression artifacts. For best results you should use the original PNG image where possible.
from PIL import Image
import numpy as np
import urllib.request
import os
url = "https://user-images.githubusercontent.com/577666/281602715-84ab604f-ff85-45c4-982f-20a15c97b526.png"
filename = "worm.png"
# Download image if it does not exist yet
if not os.path.isfile(filename):
urllib.request.urlretrieve(url, filename)
image = np.array(Image.open(filename).convert("RGB").convert("RGBA"))
white = np.array([255, 255, 255, 255])
# Remove non-white pixel rows at beginning of image
while np.sum(np.abs(image[0, 0] - white)) != 0:
image = image[1:]
# Remove non-white pixel rows at end of image
while np.sum(np.abs(image[-1, 0] - white)) != 0:
image = image[:-1]
# Remove background
alpha = 255 - image[:, :, 0]
image[:, :, :3] = 0
image[:, :, 3] = alpha
image = Image.fromarray(image)
image.save(filename.replace(".png", "_with_alpha.png"))
@99991 Thank you so much for your result,
In other images generated by AI, sometime, the image has gray or small shadow. I also need remove them for colouring inside mobile app too.
Please help me give more solution for resolving all problem above (Just not white color)
Please see this image:
I also run above code but happen error
while np.sum(np.abs(image[0, 0] - white)) != 0:
IndexError: index 0 is out of bounds for axis 0 with size 0
The following code will work for the bird image.
from PIL import Image
import numpy as np
import urllib.request
import os
url = "https://camo.githubusercontent.com/53579167c3f8c1c1889634867e1dc8ab50688f39025631b25428303b8612a6d6/68747470733a2f2f736770312e6469676974616c6f6365616e7370616365732e636f6d2f6666682d73706163652d30312f62616279636172652f75706c6f6164732f6174746163686d656e742f6c696e6b2f373135332f6f7374726963682e706e67"
filename = "bird.png"
if not os.path.isfile(filename):
urllib.request.urlretrieve(url, filename)
image = np.array(Image.open(filename).convert("RGB").convert("RGBA")) / 255.0
average = image[:10, :10, 0].mean()
alpha = np.clip((average - image[:, :, 0]) / average, 0, 1)
image = np.zeros_like(image)
image[:, :, 3] = alpha
image = np.clip(image * 255, 0, 255).astype(np.uint8)
image = Image.fromarray(image)
image.save(filename.replace(".png", "_with_alpha.png"))
This issue is stale because it has been open for 30 days with no activity.
I have a picture and want to remove all background. But current model only remove outside background
Here is result, still have white inside caterpilar
Please help me. Thank you so much!