简体   繁体   English

使用PIL或Scipy将Python图像从RGB转换为单通道

[英]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) 是否有一种已知的解决方案,可以使用PIL(或Scipy)将图像从具有3个通道( RGB )转换为仅具有一个通道

I tried converting the image to Grayscale and saving as png as per the code below, the image still had 3 color channels. 我尝试将图像转换为Grayscale并按照以下代码另存为png,图像仍然具有3个颜色通道。

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

I tried just using im.convert('L') but that replaced the transparency with black (turning my entire image black). 我尝试仅使用im.convert('L')但是将其替换为黑色(将整个图像im.convert('L')黑色)。

I found the below code from Remove transparency/alpha from any image using PIL extremely helpful (full credits to Humphrey): 我发现使用PIL从任何图像删除透明度/ alpha中的以下代码非常有帮助(对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.convert('L')进行转换,将返回灰度模式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM