Search code examples
pythonimage-processingopencvscikit-imagegrayscale

Removing alpha channels from grayscale images


I have some B&W images, but in RGBa. I used skimage rgb2gray(inp_image) to convert them into grayscale. Yet they become grayscale images with alpha channel.

What do I do if I want to have those RGBa converted to grayscale without alpha channel?


Solution

  • You can try out this.

    import cv2
      
    image = cv2.imread('path to your image')
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
      
    cv2.imshow('Gray image', gray)
      
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    for multiple images

    import cv2
    from os import listdir,makedirs
    from os.path import isfile,join
    
    source = r'path to source folder'
    destination = r'path where you want to save'
    
    files = [f for f in listdir(source) if isfile(join(source,f))] 
    
    for image in files:
        try:
            img = cv2.imread(os.path.join(source,image))
            gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
            dstPath = join(destination,image)
            cv2.imwrite(destination,gray)
        except:
            print ("{} is not converted".format(image))