0

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

karlphillip
  • 92,053
  • 36
  • 243
  • 426
open source guy
  • 2,727
  • 8
  • 38
  • 61

2 Answers2

6

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)
rsalmond
  • 405
  • 3
  • 7
  • this limits to those PNGs that originally has alpha channels. For those PNGs with RGB channels only, alpha channel has to be added beforehand. – Raptor Oct 20 '22 at 03:28
4

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.

Community
  • 1
  • 1
karlphillip
  • 92,053
  • 36
  • 243
  • 426