11

I am loading images from a URL in OpenCV. Some images are PNG and have four channels. I am looking for a way to remove the 4th channel, if it exists.

This is how I load the image:

def read_image_from_url(self, imgurl):
    req = urllib.urlopen(imgurl)
    arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
    return cv2.imdecode(arr,-1) # 'load it as it is'

I don't want to change the cv2.imdecode(arr,-1) but instead I want to check whether the loaded image has a fourth channel, and if so, remove it.

Something like this but I don't know how to actually remove the 4th channel

def read_image_from_url(self, imgurl):
    req = urllib.urlopen(imgurl)
    arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
    image = cv2.imdecode(arr,-1) # 'load it as it is'
    s = image.shape
    #check if third tuple of s is 4
    #if it is 4 then remove the 4th channel and return the image. 
Harald K
  • 26,314
  • 7
  • 65
  • 111
Anthony
  • 33,838
  • 42
  • 169
  • 278

3 Answers3

26

You need to check for the number of channels from img.shape and then proceed accordingly:

# In case of grayScale images the len(img.shape) == 2
if len(img.shape) > 2 and img.shape[2] == 4:
    #convert the image from RGBA2RGB
    img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
ZdaR
  • 22,343
  • 7
  • 66
  • 87
3

This could also work.

if len(img.shape) > 2 and img.shape[2] == 4:
    #slice off the alpha channel
    img = img[:, :, :3]

reference post

Anik De
  • 73
  • 5
0

Read this: http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html

cv2.imdecode(buf, flags)

if flags is < 0 as in your case (-1) you will get the image as is. if flags is > 0 it will return a 3 channel image. alpha channel is stripped. flags == 0 will result in a gray scale image

cv2.imdecode(arr,1) should result in a 3 channel output.

Piglet
  • 27,501
  • 3
  • 20
  • 43
  • Yeah, there are certain images that I want AS -IS. thats why I'm reluctant to change the flag but instead do a check if there is a 4th layer and only then remove it. – Anthony Apr 26 '16 at 18:15
  • then you should ask how to check if there is a 4th channel, not how to remove it... – Piglet Apr 26 '16 at 18:16
  • this flag will also impact bit depth so that is not a good solution for removing the alpha channel – Gil Hiram Nov 16 '17 at 08:02