Reputation: 295
So say I have an image, and I want to make it so that only the red channel shows up, and the image looks red, how would I do this using PIL? Thanks.
Upvotes: 9
Views: 18665
Reputation: 1366
For people who are looking to extract a single channel from an image (as opposed to generating an image with R, G and B channels, but with the G and B channels all zero), you can do:
img = Image.open("image.jpg")
red = img.getchannel('R')
# OR
red = img.getchannel(0) # Avoids internal lookup of 'R' in img.getbands()
Upvotes: 1
Reputation: 456
Late here, but because we're dealing with numpy, we can use boolean indexing.
def channel(img, n):
"""Isolate the nth channel from the image.
n = 0: red, 1: green, 2: blue
"""
a = np.array(img)
a[:,:,(n!=0, n!=1, n!=2)] *= 0
return Image.fromarray(a)
Upvotes: 2
Reputation: 7691
You can use the Image.split()
operation from PIL to separate the image into bands:
img = Image.open("image.jpg")
red, green, blue = img.split()
If the image has an alpha channel (RGBA) the split function will aditionaly return that. More information here.
Upvotes: 16
Reputation: 295
I found the answer. Instead of using im.split(), which converted the band to grayscale, I should've converted the Image to an array,multiplied the bands I don't want by 0, and then turned it back to an Image object.
Importing Image and numpy, I did the following:
a = Image.open("image.jpg")
a = numpy.array(a)
a[:,:,0] *=0
a[:,:,1] *=0
a = Image.fromarray(a)
a.show()
This would show a blue image.
Upvotes: 8