'Fastest way to remove white background from image/video

I need to make the below faster as I need it to run on a video. Basically I am trying to remove a white background on a video and then overlay that onto another video. The below is what I have tried but it takes to long to process.

im = im.convert("RGBA")
datas = im.getdata()
newData = []
for item in datas:
    print(item)
    if item[0] == 255 and item[1] == 255 and item[2] == 255:
        newData.append((255, 255, 255, 0))
    else:
        newData.append(item)

im.putdata(newData)


Solution 1:[1]

You could use Numpy in Python/OpenCV (or PIL) to replace white with transparent, since you seem to already have 4 channels in your 'im' image with presumably opaque alpha channel.

import numpy as np
import cv2

# read image
im = cv2.imread('logo.png')

# convert to 4 channels (bgr with opaque alpha)
im = cv2.cvtColor(im, cv2.COLOR_BGR2BGRA)

# replace white with transparent using Numpy
new_im = im.copy()
new_im[np.where((im==[255,255,255,255]).all(axis=2))] = [255,255,255,0]

# write result to disk
cv2.imwrite("logo_transparent.png", new_im)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fmw42