是否有已知的解决方案将图像从3个通道( RGB )转换为只使用PIL(或Scipy)的一个通道
我尝试将图片转换为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
答案 0 :(得分:2)
我尝试使用im.convert('L')
,但用黑色取代透明度(将整个图像变黑)。
我发现Remove transparency/alpha from any image using PIL的以下代码非常有帮助(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
首先删除透明度,然后使用im.convert('L')
进行转换,将返回灰度模式:
im = remove_transparency(im).convert('L')