Skip to content

Instantly share code, notes, and snippets.

@IAmSuyogJadhav
Created November 1, 2018 21:56
Show Gist options
  • Save IAmSuyogJadhav/1701abb6bd97568783997c4d4e211c50 to your computer and use it in GitHub Desktop.
Save IAmSuyogJadhav/1701abb6bd97568783997c4d4e211c50 to your computer and use it in GitHub Desktop.
import cv2
import numpy as np
image_path = 'path/to/image' # Path to the input image
bgcolor = [255, 255, 255] # BGR value of background color.
img = cv2.imread(image_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
img[np.all(img == bgcolor + [255], axis=2)] = [0,0,0,0]
cv2.imwrite('output.png', img) # File will be saved as output.png in the current directory.
@IAmSuyogJadhav
Copy link
Author

@Xaalek, this kind kf background removal only works when the image in question has a uniform background (usually the case with digitally created images). For most other images, you'll need to perform some kind of thresholding on the image such that all the background pixels bear the same value and then use this. This thresholding shall vary from dataset to dataset.

If you are looking to remove background from a single image, there are multiple websites these days that do this for you. One really good one that I know of is remove.bg. I think they also offer API.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment