Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 600
Monica Heddneck Avatar asked May 08 '18 23:05

Monica Heddneck


2 Answers

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')
like image 94
wwii Avatar answered Nov 06 '22 15:11

wwii


just use:

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

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

like image 23
MarStarck Avatar answered Nov 06 '22 15:11

MarStarck