gpt4 book ai didi

python - 使用 PIL 或 Scipy 将 Python 图像从 RGB 转换为单 channel

转载 作者:行者123 更新时间:2023-12-02 00:44:03 24 4
gpt4 key购买 nike

是否有一种已知的解决方案可以使用 PIL(或 Scipy)将图像从具有 3 个 channel (RGB)转换为只有一个 channel

我尝试将图像转换为 Grayscale 并按照下面的代码保存为 png,图像仍然有 3 个颜色 channel 。

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

最佳答案

我尝试只使用 im.convert('L') 但它用黑色替换了透明度(将我的整个图像变成黑色)。

我从 Remove transparency/alpha from any image using PIL 中找到了以下代码非常有帮助(汉弗莱的全部学分):

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')

关于python - 使用 PIL 或 Scipy 将 Python 图像从 RGB 转换为单 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44997339/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com