Home > Net >  I'm trying to remove the background of an image
I'm trying to remove the background of an image

Time:11-19

How can I remove the white background of an image with a code? I've tried this, but didn't work:

import cv2

RED =0
GREEN =0
BLUE =0
ALPHA =0

Image = cv2.imread("D:\\PYTHON_bkground\\bkg\\sagitale1.png", cv2.IMREAD_UNCHANGED)

trans_mask = Image[:,:,3 ]==0

Image[trans_mask]=[BLUE, GREEN, RED, ALPHA]

print(Image.shape)
resized = cv2.resize(Image, None, fx=0.1, fy=0.1)
cv2.imshow('windows', resized)
cv2.waitKey(0)

this error appears: Traceback (most recent call last): File "d:\PYTHON_bkg1\bkg\bkg.py", line 12, in <module> trans_mask = Image[:,:,3 ]==0 TypeError: 'NoneType' object is not subscriptable

image

CodePudding user response:

You can remove the white background easily using pillow module python as follows.

from PIL import Image


def convertImage():
    img = Image.open("d.png")
    img = img.convert("RGBA")
  
    datas = img.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)
  
    img.putdata(newData)
    img.save("pic.png", format="png")
  
convertImage()

enter image description here

  • Related