简体   繁体   English

Python PIL 图像拆分为 RGB

[英]Python PIL image split to RGB

How to split image to RGB colors and why doesn't split() function work?如何将图像分割为 RGB 颜色,为什么split()函数不起作用?

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?为什么red.show()以灰度而不是红色显示图像?

PS.附注。 The same situation using green.show() and blue.show() .使用green.show()blue.show()情况相同。

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 图像,并通过抑制我们不想要的波段来为每个波段创建像素数据。

RGB to R__ -> red.png RGBR__ -> red.png

RGB to _G_ -> green.png RGB_G_ -> green.png

RGB to __B -> blue.png RGB__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')

在此处输入图片说明在此处输入图片说明在此处输入图片说明在此处输入图片说明

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.如果您希望它以本机颜色显示(即红色“R”通道、蓝色“B”通道、绿色“G”通道),您需要连接 3 个通道并将您不感兴趣的通道归零。记住维护通道订购,这样您就不会得到红色的“G”通道。

Might be easier to simple take 3 copies of the image and zero the irrelevant channels rather than using split.可能更容易简单地获取图像的 3 个副本并将不相关的通道归零,而不是使用拆分。

You can use either OpenCV or Pillow.您可以使用 OpenCV 或 Pillow。 It's simple in both.两者都很简单。 I've written a class (Uses Pillow, https://github.com/mujeebishaque/image-splitter ) that you can utilize and get all the channels saved in the current directory just by calling a function.我编写了一个类(使用枕头, https://github.com/mujeebishaque/image-splitter ),您只需调用一个函数即可利用并获取当前目录中保存的所有频道。

In OpenCV, you'd use the method split() on the image to get RGB or RGBA channels.在 OpenCV 中,您将在图像上使用split()方法来获取 RGB 或 RGBA 通道。

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

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