Qwertford
Qwertford

Reputation: 1189

How to set white pixels to transparent using OpenCV

My code so far. I want to crop out the white in the image.

import cv2
import numpy as np

image = cv2.imread('myimage.jpg')
image2 = np.ones((255, 255, 4))
for i in range(255):
    for j in range(255):
        if image[i,j,0] == 255: 
            image2[i, j, :] = np.append(image[i, j, :], 1)
        else:
            image2[i, j, :] = np.append(image[i, j, :], 1)

cv2.imwrite('image2.png', image2)

But it just produces an empty plot.

Upvotes: 4

Views: 4956

Answers (1)

Berriel
Berriel

Reputation: 13601

This should be enough:

The background of the website is white, so "right click" the Output and "open image in new tab" and you'll see that it is transparent :)

import cv2
import numpy as np

# read the image
image_bgr = cv2.imread('image_bgr.png')
# get the image dimensions (height, width and channels)
h, w, c = image_bgr.shape
# append Alpha channel -- required for BGRA (Blue, Green, Red, Alpha)
image_bgra = np.concatenate([image_bgr, np.full((h, w, 1), 255, dtype=np.uint8)], axis=-1)
# create a mask where white pixels ([255, 255, 255]) are True
white = np.all(image_bgr == [255, 255, 255], axis=-1)
# change the values of Alpha to 0 for all the white pixels
image_bgra[white, -1] = 0
# save the image
cv2.imwrite('image_bgra.png', image_bgra)
  • Input:

Input

  • Output ("right click" >> "open in new tab"):

Output

Upvotes: 4

Related Questions