Python PIL image split to RGB

落爺英雄遲暮 提交于 2019-12-24 05:06:13

问题


How to split image to RGB colors and why doesn't split() function work?

from PIL import Image
pil_image = Image.fromarray(some_image)
red, green, blue = pil_image.split()
red.show()

Why does red.show() shows image in greyscale instead of red scale?

PS. The same situation using green.show() and blue.show().


回答1:


I've created a script that takes an RGB image, and creates the pixel data for each band by suppressing the bands we don't want.

RGB to R__ -> red.png

RGB to _G_ -> green.png

RGB to __B -> blue.png

from PIL import Image

img = Image.open('ra.jpg')
data = img.getdata()

# Suppress specific bands (e.g. (255, 120, 65) -> (0, 120, 0) for g)
r = [(d[0], 0, 0) for d in data]
g = [(0, d[1], 0) for d in data]
b = [(0, 0, d[2]) for d in data]

img.putdata(r)
img.save('r.png')
img.putdata(g)
img.save('g.png')
img.putdata(b)
img.save('b.png')




回答2:


A single channel image will always show as grayscale. If you want it to show in native colours (ie a red "R" channel, blue "B" channel, green "G" channel) you need to concatenate 3 channels and zero the ones you are not interested in. Remember to maintain channel order so that you don’t get a red "G" channel.

Might be easier to simple take 3 copies of the image and zero the irrelevant channels rather than using split.



来源:https://stackoverflow.com/questions/51325224/python-pil-image-split-to-rgb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!