Julian Wise
Julian Wise

Reputation: 378

Convert Python image to Single Channel from RGB using PIL or Scipy

Is there a known solution to convert images from having 3 channels (RGB) to having only one channel using PIL (or Scipy)

I tried converting the image to Grayscale and saving as png as per the code below, the image still had 3 color channels.

from glob import glob
import os
import os.path
from PIL import Image

SIZE = 32, 32

# set directory
# os.chdir('..data/unprocessed_cats')

# filter all jpg and png images
IMAGE_FILES = glob('../data/validation/cats/*.jpg')

IMAGE_COUNTER = 1
print IMAGE_FILES
# iterate over files
for image_file in IMAGE_FILES:

    # open file and resize
    try:
        im = Image.open(image_file)
    except:
        pass
    im = im.resize(SIZE, Image.ANTIALIAS)

    # save locally
    output_filename = "%s.png" % IMAGE_COUNTER
    # Grayscale
    im.convert('LA').save(os.path.join('../data/validation', 'cats_processed', output_filename), "PNG")


    # incriment image counter
    IMAGE_COUNTER = IMAGE_COUNTER + 1

Upvotes: 2

Views: 12417

Answers (1)

yl_low
yl_low

Reputation: 1323

I tried just using im.convert('L') but that replaced the transparency with black (turning my entire image black).

I found the below code from Remove transparency/alpha from any image using PIL extremely helpful (full credits to Humphrey):

def remove_transparency(im, bg_colour=(255, 255, 255)):

    # Only process if image has transparency 
    if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info):

        # Need to convert to RGBA if LA format due to a bug in PIL 
        alpha = im.convert('RGBA').split()[-1]

        # Create a new background image of our matt color.
        # Must be RGBA because paste requires both images have the same format

        bg = Image.new("RGBA", im.size, bg_colour + (255,))
        bg.paste(im, mask=alpha)
        return bg

    else:
        return im

Removing the transparency first and then converting it with im.convert('L') returns the greyscale mode:

im = remove_transparency(im).convert('L')

Upvotes: 6

Related Questions