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

Monica Heddneck picture Monica Heddneck · May 9, 2018 · Viewed 8.9k times · Source

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.

Answer

wwii picture wwii · May 9, 2018

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')