0

I want to remove this image's black background.How can I do that in python? I have already tried doing it through opencv but it doesn't work

import numpy as np
import matplotlib.pyplot as plt
import cv2
from PIL import Image




# CODE TO ELIMINATE BLACK BACKGROUND
def remove_background(image):
  image = image.convert("RGBA")
  datas = image.getdata()
  newData = []
  for item in datas:
    if item[0] == 255 and item[1] == 255 and item[2] == 255:
      newData.append((255,0,0,0))
  else:
    newData.append((item))
  image.putdata(newData)
  transparent_image = np.asarray(image)
  return transparent_image


# remove background
bozu = Image.open("QWERTY.png")
transparent_bozu = remove_background(bozu)

from google.colab.patches import cv2_imshow

cv2_imshow(transparent_bozu)

plt.imshow(transparent_bozu)
plt.show()

1 Answers1

3

Your loop is removing white pixels, not black (RGB value (255,255,255). Black is (0,0,0)). Also, use numpy rather than looping through the data manually and using lists:

import numpy as np
import PIL

def remove_background(image: PIL.Image):
  image = np.asarray(image.convert("RGBA"))
  idx = (image[...,:3] == np.array((0,0,0))).all(axis=-1)
  im[idx,3] = 0
  return PIL.Image.fromarray(im)

The relevant line is:

idx = (image[...,:3] == np.array((0,0,0))).all(axis=-1)

First, you find all pixels in the image that have RGB value (0,0,0). The .all() at the end is to ensure that you get only the pixels where all three values are 0, not just on of them.

Then, using this index, you zero out the alpha channel in the pixels where the index is True:

im[idx,3] = 0
GPhilo
  • 18,519
  • 9
  • 63
  • 89