Monica Heddneck
Monica Heddneck

Reputation: 3135

How to convert a 1 channel image into a 3 channel with PIL?

I have an image that has one channel. I would like duplicate this one channel such that I can get a new image that has the same channel, just duplicated three times. Basically, making a quasi RBG image.

I see some info on how to do this with OpenCV, but not in PIL. It looks easy in Numpy, but again, PIL is different. I don't want to get into the habit of jumping from library to library all the time.

Upvotes: 9

Views: 18704

Answers (2)

MarStarck
MarStarck

Reputation: 443

just use:

image = Image.open(image_info.path).convert("RGB")

can convert both 1-channel and 4-channel to 3-channel

Upvotes: 6

wwii
wwii

Reputation: 23783

Here's one way without looking too hard at the docs..

fake image:

im = Image.new('P', (16,4), 127)

Get the (pixel) size of the single band image; create a new 3-band image of the same size; use zip to create pixel tuples from the original; put that into the new image..

w, h = im.size
ima = Image.new('RGB', (w,h))
data = zip(im.getdata(), im.getdata(), im.getdata())
ima.putdata(list(data))

Or even possibly

new = im.convert(mode='RGB')

Upvotes: 7

Related Questions