Reputation: 51
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()
.
Upvotes: 5
Views: 19640
Reputation: 2701
You can use either OpenCV or 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.
In OpenCV, you'd use the method split()
on the image to get RGB or RGBA channels.
Upvotes: 1
Reputation: 1228
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')
Upvotes: 16
Reputation: 1163
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.
Upvotes: 1