open source guy
open source guy

Reputation: 2787

How particular pixel to transparent in opencv python?

I have image messi.jpeg .I want to replace pixel with color (0,111,111) to transparent in messi.jpeg. now. my code is give below.

 img[np.where((img == [0,111,111]).all(axis = 2))] = [255,255,255]

I want transparent pixel. now it converted to white

Upvotes: 1

Views: 5445

Answers (2)

rsalmond
rsalmond

Reputation: 413

For those arriving from Google the above answer may have been true at the time it was written but as the docs describe it is no longer accurate. Passing a negative value to imread returns an array with an alpha channel.

In python this does the job:

>>> im = cv2.imread('sunny_flat.png', -1)
>>> im
array([[[ 51,  44,  53, 255],
    [ 46,  40,  46, 255],
    [ 40,  31,  36, 255],
    ..., 
    [ 24,  26,  36, 255],
    [ 26,  28,  39, 255],
    [ 15,  17,  27, 255]]], dtype=uint8)
>>> im[0][0] = np.array([0,0,0,0], np.uint8)
>>> im
array([[[  0,   0,   0,   0],
    [ 46,  40,  46, 255],
    [ 40,  31,  36, 255],
    ..., 
    [ 24,  26,  36, 255],
    [ 26,  28,  39, 255],
    [ 15,  17,  27, 255]]], dtype=uint8)

Upvotes: 7

karlphillip
karlphillip

Reputation: 93468

OpenCV doesn't support transparency (natively), sorry.

One approach is to add another channel to the image to represent the alpha channel. However, OpenCV can't display RGBA images, so upon loading an RGBA image ignore the 4th channel to display it correctly.

Upvotes: 4

Related Questions