Guanlin Chen
Guanlin Chen

Reputation: 69

How to remove an image's background and make it transparent?

The code I use is this:

from PIL import Image
import os

path = 'C:/Users/User/Desktop/GF_BSIF/temp'
newData = []

for image in os.listdir(path):
    img = Image.open(path+'/'+image)
    img = img.convert("RGBA")
    datas = img.getdata()

    for item in datas:
        if item[0] == 255 and item[1] == 255 and item[2] == 255:
            newData.append((255, 255, 255, 0))
        else:
            if item[0] > 150:
                newData.append((0, 0, 0, 255))
            else:
                newData.append(item)
                print(item)

img.putdata(newData)
img.save('C:/Users/User/Desktop/GF_BSIF/temp'+'/'+"open_science_logo_transparent.png", "PNG")

Original:

enter image description here

Result:

enter image description here

The result does not exactly make the background transparent.

How to improve the code and make the black background into transparent?

EDIT:

from PIL import Image
import matplotlib.pyplot as plt
import os
import shutil
path = 'C:/Users/User/Desktop/GF_BSIF/temp'
out_put = 'C:/Users/User/Desktop/data science/cropped'
newData = []


for image in os.listdir(path):
    img = Image.open(path+'/'+image)
    img = img.convert("RGBA")
    datas = img.getdata()
    
    for item in datas:
        if all(i == 0 for i in datas[0:3]):
            newData.append((0, 0, 0, 0))
        else:
            etcetcetc
img.putdata(newData)
img.save('C:/Users/User/Desktop/GF_BSIF/temp'+'/'+"open_science_logo_transparent.png", "PNG")   

@NotActuallyErik

It shows an error


TypeError Traceback (most recent call last)

in 14 15 for item in datas: ---> 16 if all(i == 0 for i in datas[0:3]): 17 newData.append((0, 0, 0, 0)) 18 else:

TypeError: sequence index must be integer, not 'slice'.

How to make it right?

Upvotes: 0

Views: 398

Answers (1)

NotActuallyErik
NotActuallyErik

Reputation: 21

Your code is telling PIL to remove replace every white pixel with a black one: [255,255,255,0] -> [0,0,0,255] which is why your black background remains while only the full-white spots get removed. You need to do the opposite to remove the background, i.e [0,0,0,255] -> [0,0,0,0]

this might work

for item in datas:
    if all(i == 0 for i in datas[0:3]):
        newData.append((0, 0, 0, 0))
    else:
        etcetcetc

Upvotes: 2

Related Questions